--- name: Jinja contributors: - ["AdaĆas Magdiel", "https://github.com/AdaiasMagdiel"] filename: learn-jinja.j2 --- ## Getting Started with Jinja Jinja is a fast, expressive, and extensible templating engine for Python applications. Jinja includes a lot of functionalities, such as: - Template inheritance and inclusion; - Defining and importing macros within templates; - Security mechanisms to prevent XSS attacks; - A sandboxed environment that can safely render untrusted templates; - Extensible filters, tests, functions, and even syntax. A Jinja template is simply a text file. Jinja doesn't require a specific extension, but it's common to use `.j2` or `.jinja` to make it easier for some IDEs. There are a few kinds of delimiters. The default Jinja delimiters are configured as follows: - `{% ... %}` for Statements - `{{ ... }}` for Expressions to print to the template output - `{# ... #}` for Comments not included in the template output ```jinja {# This is an example of a comment. #} {# You can use this syntax to write multiline comments as well. #} ``` ## VARIABLES ```jinja {# You have the option to access variables from the context passed to the template #} {{ foo }} {# Additionally, you can use a dot (.) to access attributes of a variable or use Python syntax, using [] #} {{ foo.bar }} {{ foo['bar'] }} {# Within the template, you can define variables as well #} {% set name = "Magdiel" %} {{ name }} ``` ## Loops ```html
{{ key }}
-{{ value }}
{% endfor %}{{ message.content }}
{% elif message.status == "success" %}{{ message.content }}
{% else %}{{ message.content }}
{% endif %} ``` ## Template Inheritance One of the most powerful features of Jinja is template inheritance. You can create a base layout with predefined blocks that you can extend in another file and override with your own content. ```html {# file: base.html.j2 #} {% block head %}Welcome to my home homepage.
{% endblock %} {# RESULT #}Welcome to my home homepage.
I'm the {{ name }} and i like to {{ hobby }}.
{# file: index.html.j2 #} {% set name = "Captain Nemo" %} {% set hobby = "navigate through the depths of the ocean" %}I'm the Captain Nemo and i like to navigate through the depths of the ocean.
{{ input(placeholder="Your username") }}
{{ input(type="password") }}
``` ## Official Documentation To learn more, access the [official documentation](https://jinja.palletsprojects.com/en/).