for
Iterate over arrays, slice, and other objects.
for
Used to iterate over each item in the array, making the item available in the context variable.
Example Code
For example, to display the document list provided by archiveList:
{% for item in archives %}
<li class="item">
<a href="/archive/{{item.Id}}" class="link">
<h5 class="title">{{item.Title}}</h5>
</a>
</li>
{% endfor %}
The program can also output the count in the for loop, as well as the remaining quantity, and it can also be used.pluralize
Determine if the number is plural. For example:
{% for item in archives %}
<li class="item">
<a href="/archive/{{item.Id}}" class="link">
<h5 class="title">第{{ forloop.Counter }}篇,剩余{{ forloop.Revcounter}}篇,{{ forloop.Revcounter|pluralize:"多于1篇" }}:{{item.Title}}</h5>
</a>
</li>
{% endfor %}
for
It can also be used.reversed
Reverse the array,sorted
Sort the array by int. For example:
{% for item in archives reversed %}
<li class="item">
<a href="/archive/{{item.Id}}" class="link">
<h5 class="title">{{item.Title}}</h5>
</a>
</li>
{% endfor %}
{% for item in archives sorted %}
<li class="item">
<a href="/archive/{{item.Id}}" class="link">
<h5 class="title">{{item.Title}}</h5>
</a>
</li>
{% endfor %}
{% for item in archives reversed sorted %}
<li class="item">
<a href="/archive/{{item.Id}}" class="link">
<h5 class="title">{{item.Title}}</h5>
</a>
</li>
{% endfor %}
for
Also supports checking if the array is empty or null, using:empty
To output the non-existent situation. For example:
{% for item in archives %}
<li class="item">
<a href="/archive/{{item.Id}}" class="link">
<h5 class="title">{{item.Title}}</h5>
</a>
</li>
{% empty %}
<div>没有内容</div>
{% endfor %}
It is equivalent to using an if statement, but it can be written more concisely:
{% if archives %}
{% for item in archives %}
<li class="item">
<a href="/archive/{{item.Id}}" class="link">
<h5 class="title">{{item.Title}}</h5>
</a>
</li>
{% endfor %}
{% else %}
<div>没有内容</div>
{% endif %}
cycle
tags. In a for loop, we can also usecycle
Tags, to loop and output each variable in the definition one by one.
Each time thiscycle
When a tag is used, it will always produce one of its parameters.The first parameter is generated when it is encountered for the first time, the second parameter is generated when it is encountered for the second time, and so on.Once all parameters are exhausted, the marker will loop back to the first parameter and generate it again.
This tag is especially useful in loops. For example:
{% for item in archives %}
<li class="item">
<a href="/archive/{{item.Id}}" class="link">
<h5 class="title">Title,Id 逐个出现:{% cycle item.Title item.Id %}</h5>
</a>
</li>
{% endfor %}
Or useas
to define an alias, and then output through the alias:
{% for item in archives %}
<li class="item">
<a href="/archive/{{item.Id}}" class="link">
{% cycle item.Title item.Id as cycleitem %}
<h5 class="title">Title,Id 逐个出现:{{ cycleitem }}</h5>
</a>
</li>
{% endfor %}