Jinja (template engine)

Jinja is a template engine for the Python programming language and is licensed under a BSD License. It is similar to the Django template engine but provides Python-like expressions while ensuring that the templates are evaluated in a sandbox. It is a text-based template language and thus can be used to generate any markup as well as sourcecode.

The Jinja template engine allows customization of tags,[1] filters, tests, and globals.[2] Also, unlike the Django template engine, Jinja allows the template designer to call functions with arguments on objects. Jinja is Flask's default template engine.[3]

Features

Some of the features of Jinja are:[4]

Jinja, like Smarty, also ships with an easy-to-use filter system similar to the Unix pipeline.

Example

Here is a small example of a template file 'example.html.jinja'[5]

<!DOCTYPE html>
<html>
  <head>
    <title>{{ variable|escape }}</title>
  </head>
  <body>
  {%- for item in item_list %}
    {{ item }}{% if not loop.last %},{% endif %}
  {%- endfor %}
  </body>
</html>

and templating code:

from jinja2 import Template
with open('example.html.jinja') as f:
    tmpl = Template(f.read())
print tmpl.render(
    variable = 'Value with <unsafe> data',
    item_list = [1, 2, 3, 4, 5, 6]
)

This produces the HTML string:

<!DOCTYPE html>
<html>
  <head>
    <title>Value with &lt;unsafe&gt; data</title>
  </head>
  <body>
    1,
    2,
    3,
    4,
    5,
    6
  </body>
</html>

Sources

  1. "Extensions". Jinja2 Documentation (2.8-dev). Retrieved 2015-05-26.
  2. "Extensions". Jinja2 Documentation (2.8-dev). Retrieved 2015-05-26.
  3. DuPlain, R. (2013). Instant Flask Web Development. Packt Publishing. p. 30. ISBN 978-1-78216-963-5. Retrieved 2015-05-26.
  4. http://jinja.pocoo.org/docs/dev/3
  5. Ronacher, Armin. "Template Designer Documentation". Jinja2 Documentation. Retrieved 7 January 2016. A Jinja template doesn’t need to have a specific extension: .html, .xml, or any other extension is just fine.

External links

This article is issued from Wikipedia - version of the Tuesday, January 12, 2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.