Jinja (template engine)
Jinja is a web template engine for the Python programming language. It was created by Armin Ronacher and is licensed under a BSD License. Jinja 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 source code. The Jinja template engine allows customization of tags,[3] filters (for formatting or transforming values[4]), tests (for evaluating conditions[4]), and globals.[5] 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 [6] and it is also used by Ansible,[7] Trac, and Salt.[8] It is also used to make SQL macros, for example for use with dbt.[9] FeaturesSome of the features of Jinja are:[10]
Jinja, like Smarty, also ships with an easy-to-use filter system similar to the Unix pipeline. SyntaxThe syntax for printing output in Jinja is using the double curly braces, for example Statements which set variables in jinja or those which do not have an output can be wrapped within Similar to above, comments in jinja can be written using a number sign ( The syntax for creating a filter in Jinja is a vertical bar ( The syntax for creating a test in Jinja is the keyword For loops can be used to iterate over sequences, while retaining their object properties. The following example demonstrates iterating over a list of users with {% for user in users %}
{{ user.username }}
{{ user.password }}
{% endfor %}
Although ExampleHere is a small example of a template file <!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 <unsafe> data</title>
</head>
<body>
1,
2,
3,
4,
5,
6
</body>
</html>
Note the minus sign ( References
External links |