forTraverse arrays, slice and other objects.
forUsed 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 %}
You can also output the count of the for loop, as well as the remaining quantity, and you can also usepluralizeDetermine if the quantity 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 %}
forIt can also be used.reversedReverse the array,sortedSort 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 %}
forIt supports checking if an array is empty or nil, usingemptyto output non-existent situations. 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 written in a more concise manner:
{% 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 %}
cycleLabel. In a for loop, we can also usecycleLabel to loop through and output each variable defined.
Each time we encounter thiscycleWhen a tag is encountered, it will produce one of its parameters. The first parameter is produced when it is encountered for the first time, the second parameter 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 marker 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 use:asDefine 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 %}