01-for tag
In Django templates, for
tag is an important tag used for loop iteration. Its syntax is similar to the for
loop in Python, but has some special usage in Django templates. The following is a detailed introduction to Django template tagfor
:
basic grammar
{% for item in items %}
{# 循环体 #}
{
{ item }}
{% endfor %}
{% for item in items %}
: Start the loop, whereitem
is the loop variable, anditems
is the data to be iterated by the loop.{# 循环体 #}
: Template code executed inside the loop body.{ { item }}
: Display the value of the loop variable.{% endfor %}
: End the loop.
Note:items
is an iterable object, and this iterable object must have been generated in the view function, and you cannot generate it again in the template. That is, the following writing method is correct:
{% for line_number in context1.page_range_pc %}
<p>第{
{ line_number }}行</p>
{% endfor %}
But the way to write it is:
{% for line_number in range(context1.page_range) %}
<p>第{
{ line_number + 1 }}行</p>
{% endfor %}
It's wrong, that is, the range() function cannot be used in the for template tag.
Loop variables and empty variables
In Django templates, for
loops create a loop variable that you can use within the loop body. If the loop data is empty, you can use the empty
keyword to handle it.
{% for item in items %}
{
{ item }}
{% empty %}
<p>No items available.</p>
{% endfor %}
Filters in loop tags
You can use filters infor
loops to process data:
{% for item in items|filter:"search_query" %}
{
{ item }}
{% endfor %}
Counter in loop
If you need to get the index or count of the current loop, you can use theforloop
object:
{% for item in items %}
{
{ forloop.counter }}: {
{ item }}
{% endfor %}
forloop.counter
: The counter of the current loop, starting from 1.forloop.counter0
: The counter of the current loop, starting from 0.
Other properties in the loop
forloop
The object also has some other attributes, such as forloop.first
indicating whether the current element is the first element in the loop, forloop.last
indicating whether the current element is in the loop The last element.
{% for item in items %}
{% if forloop.first %}
First: {
{ item }}
{% elif forloop.last %}
Last: {
{ item }}
{% else %}
{
{ item }}
{% endif %}
{% endfor %}
Nested loops
Django templates support loop nesting. You can nest onefor
loop inside another.
{% for category in categories %}
<h2>{
{ category.name }}</h2>
<ul>
{% for item in category.items %}
<li>{
{ item.name }}</li>
{% endfor %}
</ul>
{% endfor %}
These are some basic usages of for
tags in Django templates. You can combine other template tags and filters to implement more complex logic according to specific needs.