for
Iterate over arrays, slices and other objects.
for
Used to iterate over each item in the array so that the item is available in the context variable.
Sample code
For example, to display a list of documents provided in archiveList:
{% for item in archives %}
<li class="item">
<a href="/archive/{{item.Id}}" class="link">
<h5 class="title">{{item.Title}}</h5>
</a>
</li>
{% endfor %}
You can also output the count of the for loop and the remaining number, and you can also use itpluralize
Determine whether the quantity is plural. like:
{% 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
Can also be usedreversed
Flip the array,sorted
Sort the array by int. like:
{% 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
It also supports determining whether it is an empty array or nil, etc.empty
to output the case that does not exist. like:
{% 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 if to judge, but writing this way can be more concise:
{% 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
Label. In the for loop, we can also usecycle
Tags to loop through output variables in definitions.
Every time I encounter thiscycle
When tagging, one of its parameters will be generated. 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 to the first parameter and produce it again.
This marker is especially useful in loops. like:
{% 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 the alias, 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 %}