formalchemy.templates – Template engines

Available engines

class formalchemy.templates.MakoEngine(**kw)
Template engine for mako. File extension is .mako.
class formalchemy.templates.GenshiEngine(**kw)
Template engine for genshi. File extension is .html.
class formalchemy.templates.TempitaEngine(**kw)
Template engine for tempita. File extension is .tmpl.

Base class

class formalchemy.templates.TemplateEngine(**kw)

Base class for templates engines

get_filename(name)
return the filename for template name
get_template(name, **kw)
return the template object for name. Must be override by engines
render(template_name, **kwargs)
render the template. Must be override by engines

Customize templates

You can override the default template by adding a directory for your project which will contain the templates. The engine will scan the directory and try to load templates from it. If he can’t, the default templates are used.

Here is an example:

>>> ls(mako_templates_dir)
- fieldset.mako

>>> cat(mako_templates_dir, 'fieldset.mako')
<ul>
%for field in fieldset.render_fields.itervalues():
<li>${field.name}</li>
%endfor
</ul>
<BLANKLINE>

Then you can override the default mako templates:

>>> from formalchemy import config
>>> from formalchemy import templates
>>> config.engine = templates.MakoEngine(
...               directories=[mako_templates_dir],
...               input_encoding='utf-8', output_encoding='utf-8')

And see the result:

>>> print FieldSet(User).render()
<ul>
<li>email</li>
<li>password</li>
<li>name</li>
<li>orders</li>
</ul>
<BLANKLINE>

Same with genshi except that formalchemy don’t provide default templates:

>>> cat(genshi_templates_dir, 'fieldset.html')
<ul xmlns:py="http://genshi.edgewall.org/">
<li py:for="field in fieldset.render_fields.itervalues()">${field.name}</li>
</ul>
<BLANKLINE>

>>> config.engine = templates.GenshiEngine(directories=[genshi_templates_dir])

And same the result of course:

>>> print FieldSet(User).render()
<ul>
<li>email</li><li>password</li><li>name</li><li>orders</li>
</ul>

Write your own engine

You need to subclass the TemplateEngine:

>>> class MyEngine(TemplateEngine):
...     def render(self, template_name, **kw):
...         return 'It works !'

You can use it for a specific FieldSet:

>>> fs = FieldSet(User)
>>> fs.engine = MyEngine()
>>> print fs.render()
It works !

You can also override the engine in a subclass:

>>> class MyFieldSet(FieldSet):
...     engine = MyEngine()

Or set it as the global engine with formalchemy‘s config:

>>> from formalchemy import config
>>> config.engine = MyEngine()

It should be available for all FieldSet:

>>> print FieldSet(User).render()
It works !

Table Of Contents

Previous topic

formalchemy.config – Global configuration

Next topic

Other customizations

This Page