| 28 | |
| 29 | ---------- |
| 30 | Python API |
| 31 | ---------- |
| 32 | |
| 33 | The Python code required for templating with Markup is generally based on the |
| 34 | following pattern: |
| 35 | |
| 36 | * Attain a ``Template`` object from a string or file object containing the |
| 37 | template XML source. This can either be done directly, or through a |
| 38 | ``TemplateLoader`` instance. |
| 39 | * Call the ``generate()`` method of the template, passing any data that should |
| 40 | be made available to the template as keyword arguments. |
| 41 | * Serialize the resulting stream using its ``render()`` method. |
| 42 | |
| 43 | For example:: |
| 44 | |
| 45 | from markup.template import Template |
| 46 | |
| 47 | tmpl = Template('<h1>$title</h1>') |
| 48 | stream = tmpl.generate(title='Hello, world!') |
| 49 | print stream.render('xhtml') |
| 50 | |
| 51 | That code would produce the following output:: |
| 52 | |
| 53 | <h1>Hello, world!</h1> |
| 54 | |
| 55 | However, if you want includes_ to work, you should attain the template instance |
| 56 | through a ``TemplateLoader``, and load the template from a file:: |
| 57 | |
| 58 | from markup.template import TemplateLoader |
| 59 | |
| 60 | loader = TemplateLoader([templates_dir]) |
| 61 | tmpl = loader.load('test.html') |
| 62 | stream = tmpl.generate(title='Hello, world!') |
| 63 | print stream.render('xhtml') |