Jinja (template engine)

From Wikipedia, the free encyclopedia
  (Redirected from Jinja2 (template engine))
Jump to: navigation, search

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.

Features[edit]

From [3]

  • sandboxed execution
  • powerful automatic HTML escaping system for XSS prevention
  • template inheritance
  • compiles down to the optimal python code just in time
  • optional ahead-of-time template compilation
  • easy to debug. Line numbers of exceptions directly point to the correct line in the template.
  • configurable syntax

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

Example[edit]

Here is a small example of a template:

from jinja2 import Template
 
tmpl = Template(u'''\
<!DOCTYPE html>
<html>
  <head>
    <title>{{ variable|escape }}</title>
  </head>
  <body>
  {%- for item in item_list %}
    {{ item }}{% if not loop.last %},{% endif %}
  {%- endfor %}
  </body>
</html>
''')
 
print tmpl.render(
    variable = 'Value with <unsafe> data',
    item_list = [1, 2, 3, 4, 5, 6]
)

This produces the HTML:

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

External links[edit]

http://pypi.python.org/pypi/Jinja2
http://github.com/mitsuhiko/jinja2
http://github.com/mitsuhiko/jinja2/issues