Engines

piecutter‘s engines use third-party template engines to generate output using template and data.

Engines are callables that accept template, data as input then return generated output as an iterable file-like object.

Warning

Engines support only single templates. Rendering collections of templates involve interactions with loaders. This feature is implemented by cutters level.

Python format

>>> import piecutter
>>> render = piecutter.PythonFormatEngine()
>>> output = render(u'Hello {who}!', {u'who': u'world'})
>>> print(output.read())
Hello world!

Jinja2

>>> import piecutter
>>> render = piecutter.Jinja2Engine()
>>> output = render(u'Hello {{ who }}!', {u'who': u'world'})
>>> print(output.read())
Hello world!

Django

>>> import piecutter
>>> render = piecutter.DjangoEngine()
>>> output = render(u'Hello {{ who }}!', {u'who': u'world'})
>>> print(output.read())
Hello world!

Proxy

This is a special renderer that tries to detect best engine matching template.

>>> import piecutter
>>> render = piecutter.ProxyEngine(
...     engines={
...         'django': piecutter.DjangoEngine(),
...         'jinja2': piecutter.Jinja2Engine(),
...         'pythonformat': piecutter.PythonFormatEngine(),
...     },
... )

>>> data = {u'who': u'world'}

>>> template = piecutter.TextTemplate("{# Jinja2 #}Hello {{ who }}!")
>>> print(render(template, data).read())
Hello world!

>>> template = piecutter.TextTemplate("{# Django #}Hello {{ who }}!")
>>> print(render(template, data).read())
Hello world!

>>> template = piecutter.TextTemplate("Hello {who}!")
>>> print(render(template, data).read())
Hello world!

Warning

piecutter.ProxyEngine is experimental and not yet optimized: it loads template content in memory in order to guess engine. Better implementations or alternatives (such as using template filename’s extension) are welcome!

Custom engines

Engines typically are classes that inherit from piecutter.Engine. Feel free to write your own!

class piecutter.engines.Engine

Bases: object

Engines render single template against data.

Subclasses MUST implement do_render(): and match().

render(template, context)

Return the rendered template against context.

match(template, context)

Return probability that template uses engine (experimental).

If a template is not written in engine’s syntax, the probability should be 0.0.

If there is no doubt the template has been written for engine, the probability should be 1.0.

Else, the probability should be strictly between 0.0 and 1.0.

As an example, here are two ways to be sure template has been written for a specific template engine:

  • template’s name uses specific file extension
  • there is an explicit shebang at the beginning of the template.