📜  jinja loop (1)

📅  最后修改于: 2023-12-03 15:02:08.019000             🧑  作者: Mango

Jinja Loop

Jinja is a modern and designer-friendly templating language for Python, modelled after Django's templates. It is widely used in Flask web framework.

Jinja Loop is one of the most powerful features in Jinja, that enables you to iterate over a sequence of items and execute the same code multiple times.

Syntax

The syntax of Jinja Loop is very similar to Python's for loop.

{% for item in sequence %}
   {{ item }}
{% endfor %}

In the above syntax, item represents the current value of the sequence, and sequence is the list, tuple, or dictionary that is being iterated.

Examples

Let's look at some examples to understand the power of Jinja Loop.

Iterating over a list

Suppose we have a list of names, and we want to display each name on a separate line.

{% for name in ['Alice', 'Bob', 'Carol'] %}
   {{ name }}
{% endfor %}

Output:

Alice
Bob
Carol

Iterating over a tuple

Suppose we have a tuple of numbers, and we want to display the sum of all numbers.

{% set numbers = (1, 2, 3, 4, 5) %}
{% set sum = 0 %}

{% for number in numbers %}
   {% set sum = sum + number %}
{% endfor %}

The sum of numbers is {{ sum }}.

Output:

The sum of numbers is 15.

Iterating over a dictionary

Suppose we have a dictionary of countries and their capitals, and we want to display the capital of each country.

{% set countries = {'USA': 'Washington D.C.', 'India': 'New Delhi', 'Japan': 'Tokyo'} %}

{% for country, capital in countries.items() %}
   The capital of {{ country }} is {{ capital }}.
{% endfor %}

Output:

The capital of USA is Washington D.C.
The capital of India is New Delhi.
The capital of Japan is Tokyo.
Conclusion

Jinja Loop is a powerful feature in Jinja, that enables you to iterate over a sequence of items and execute the same code multiple times. It is very similar to Python's for loop, and can be used to achieve complex tasks when used with other Jinja features.