Introduction to Jinja2 Syntax of Flask Template Engine

  • 2021-07-01 07:58:48
  • OfStack

Jinja is the template engine that makes up Flask. You may not know what it does yet, but you are definitely familiar with the following percent signs and braces:


{% block body %}
 <ul>
 {% for user in users %}
  <li><a href="{{ user.url }}" rel="external nofollow" >{{ user.username }}</a></li>
 {% endfor %}
 </ul>
{% endblock %}

After reading Flask Web Development, many people can write this, but besides what is said in the book, you should also know 1 other grammatical details. This article will introduce some commonly used syntax and functions. If you want to understand Jinja systematically and completely, you can read its document: Jinja2 Documentation.

FAQ

In the FAQ on the Jinja website, I picked 3 questions that you might be interested in.

1. Why is it called Jinja?

The reason why it is called Jinja is that the English word of Japanese shrine (Jinja) is temple, while the English word of template is template, and their pronunciation is very similar (so it could have been called Miao …).

2. What is the speed of Jinja?

It is similar to Mako, but 10 ~ 20 times faster than Genshi and Django template engine.

3. Is it a good idea to put logical judgments (Logic) into templates?

There is no doubt that the less logical judgments (Logic) you put in the template, the better. But in order to make everyone happy, proper logical judgment is needed. Nevertheless, it has many restrictions on what you can and cannot do.

For many reasons (speed, readability, etc.), Jinja does not allow you to place either arbitrary Python code or all Python expressions. That's why we need to know the syntax of Jinja2.

Delimiters (Delimiter)

{%...%} statement (Statements)
{{...}} Print template output expression (Expressions)
{#... #} Comments
#... # # Line statement (Line Statements)

Say one more comment, this is a single line comment:


{#% for user in users %#}

The following is a multi-line comment:


{# note: commented-out template because we no longer use this
  {% for user in users %}
    ...
  {% endfor %}
#}

Variables (variable)

In addition to ordinary string variables, Jinja2 also supports lists, dictionaries and objects. You can get variable values as follows:


{{ mydict['key'] }}
{{ mylist[3] }}
{{ mylist[myintvar] }}
{{ myobj.somemethod() }}

There are two ways to get the properties of a variable:


{{ foo.bar }}
{{ foo['bar'] }}

These two methods are basically the same (deep differences can be ignored for the time being)

Filter (Filter)

Filters are used to modify variables, separated by a vertical bar from variables.


{{ items|join(', ') }}

Commonly used built-in filters:

safe does not escape when rendering capitalize First Letter Capital lower Lowercase upper Capital title the first letter of each word is converted to uppercase trim Remove the first and last spaces striptags Remove the HTML label from the value default sets a default value, which is replaced if the variable is not defined. Something like this:

{{ my_variable|default('my_variable is not defined') }}
random (seq) returns a random element in a sequence truncate (s, length=255, killwords=False, end= '...') Intercepts articles of specified length (article abstracts) format (value, *args, **kwargs) Refer to the string formatting function of Python If the left side of length is a list, the number of lists is output; If it is a string, the length of the string is output ...

Complete list of fliter: http://jinja.pocoo.org/docs/dev/templates/# builtin-filters

Tests (Test, Judgment)

tests provided by Jinja2 can be used to test variables or expressions in statements. If you want to test a variable, you can add "is" and test names after the variable, such as:


{% if user.age is equalto 42 %} {#  It can also be written here ... is equalto(42) #}
  Ha, you are 42!
{% endif %}

If you want to pass in parameters, you can add parentheses after test, or you can write them directly after it.

Commonly used test (return True or False for unspecified ones):

defined equalto escaped none sequence string number reverse replace ......

For a complete list of test and its usage, see Template Designer Documentation

Loop (loop)

In an for loop, there are 1 special variables that can be used, which are commonly used:

loop. index Current iteration number of floors that can be used to write comments (starting from 1) loop. index0 Same as above, but iterate from 0 loop. revindex Inverse Iteration Algebra (Cardinality 1) loop. revindex0 Inverse Iteration Algebra (Cardinality 0) Number of loop. length sequences loop. Is first the first element loop. Is last the last element ......

For a complete list, see: http://jinja. pocoo. org/docs/dev/templates/# for

Whitespace Control (Space Control)

Default settings:

If there is a line break at the end, remove it; Leave other spaces as they are.

That is, the following lines:


<div>
  {% if True %}
    yay
  {% endif %}
</div>

The rendered result is this:


<div>

    yay

</div>

The blank lines occupied by the Jinja2 statement, your own output spaces, and Tab will all be preserved.

If you want to remove the blank lines occupied by Jinja2 statements, you can do this by setting the environment variables of Jinja2:


{#% for user in users %#}
0

Or add a minus sign manually like this (note that there is no space between% and%):


{#% for user in users %#}
1

Both achieve the same effect, as follows:


{#% for user in users %#}
2

If a statement block is preceded by a minus sign:


<div>
  {%- if True -%}
    yay
  {%- endif -%}
</div>

After rendering, it will look like this:


{#% for user in users %#}
4

With the environment variables provided by Jinja2, you can set many things, such as delimiters (in case of conflicts with other languages, you can modify the delimiters). For details, see: http://jinja.pocoo.org/docs/dev/api/# jinja2.Environment

Escaping (Escape)

Sometimes you want to output 1 Jinja2 statement and delimiter as it is. For small content, you can use variable expression to output, such as outputting 1 delimiter:


{#% for user in users %#}
5

Large content blocks can be wrapped in one raw block:


{#% for user in users %#}
6

Template inheritance

You can create an base. html as the base template, and place the navigation bar, footer, flash message, js or css file, etc. that need to be displayed in each page in the base template, and add an empty block to place the contents of other sub-templates:


{#% for user in users %#}
7

Then use this extends statement in other templates (sub-templates) to inherit it, and place the corresponding contents into the empty blocks defined in the base template:


{% extends "base.html" %}
{% block content %}
 Content of the sub-template 
{% endblock %}

If you want to add content to a block already defined in the parent template, you can use the super function:


{#% for user in users %#}
9

This avoids overwriting the contents of the parent block.

Global function

Common global functions are:

range([start, ]stop[, step]) lipsum (n=5, html=True, min=20, max=100) generates a number of lorem ipsum for the template.

See Template Designer Documentation for a detailed list

Other content

There are many other contents, such as line statements, control flows, expressions, macros and so on. No more 11 introduction (writing this kind of introduction article is too tired …).

See the template section of the document for details:

Template Designer Documentation

Related links

Jinja Home Page: Jinja2 Documentation

Jinja2 Documentation: Jinja2 Documentation

Jinja2 Document Template Section: Template Designer Documentation

Github Project Page: pallets/jinja


Related articles: