Basics of Jinja Syntax
Now that we are familiar with the basics of rendering a jinja template and passing data to it with a python program, we proceed to the basic syntax of the jinja templates and how to use the data passed in the template.
Delimiters
All the jinja syntax goes inside the delimiters inside the template. All the text outside the delimiters is rendered as it is. There are following three types of delimiters by default –
- {{ }} for expressions.
- {# #} for comments (even multiline) inside the template.
- {% %} for jinja statements (like loops, etc.)
Expressions
We can write expressions inside the Jinja templates in “{{ }}” delimiters. We can even access the variables passed to the template by the rendering python program via render method as stated earlier. The delimiter is replaced with the result obtained after evaluating the expression while rendering.
Decisions
We can write the if…else statements inside the jinja template using the following syntax –
{% if <condition> %} <if block>
{% elif <condition2> %} <elif block>
<%else%> <else block
<% endif %>
Where elif and else blocks are optional. Depending on the condition, the text inside the respective block is rendered.
Loops
Jinja provides a for loop very similar to the python for loop. It works on an sequence/collection of values. It even has the range() function. Here is the syntax for the for loop in Jinja –
{% for <variable name> in <sequence> %}
<block inside the loops>
{% endfor %}
Getting started with Jinja Template
This article introduces Jinja and then describes the basics of working with it which includes how to render templates using Jinja and Python3, passing data to the template through arguments, and basic Jinja syntax (delimiters, expressions, control structures – decisions and loops). A few examples including creating a simple static HTML page are presented.
Contact Us