Website content needs to be constantly updated, such as displaying the latest articles, products, user comments, or navigation menus, and this dynamic data is often presented in the form of lists.In AnQi CMS, by using its powerful template engine and intuitive
The Anqi CMS template engine draws on the simplicity and efficiency of Django template syntax, making it easy for even developers who are new to it to quickly get started.Among them, the "loop traversal tag (for)" is the core tool we use to handle dynamic data lists, which helps us traverse various types of collection data and display its content one by one.
Get to know the 'Loop Iteration Tag (for)'
The basic syntax of the 'Loop Iteration Tag (for)' is very intuitive:
{% for item in collection %}
{# 在这里显示每一个 item 的内容 #}
{% endfor %}
Here, collectionIt refers to a collection of multiple items, such as the article list, product list, or category list obtained from the background. anditemIt represents each independent data item in the collection, in each iteration of the loop,itemwill be assigned the next element in the collection. In this way, we can accessitemvarious properties of an object, for example{{ item.Title }}(article title) or{{ item.Link }}(article link), and present it on the page.
For example, if we want to display a list of the latest articles, it might be written like this:
{% archiveList archives with type="list" limit="5" %}
{% for article in archives %}
<div class="latest-article">
<h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
<p>{{ article.Description }}</p>
</div>
{% endfor %}
{% endarchiveList %}
This code first goes througharchiveListThe tag fetched the latest 5 articles and stored them inarchivesthe variable. Then,forLoop througharchivesEach article, name itarticleAnd display the title, link, and summary of each article within the loop.
Advanced usage: Make the list smarter
The “loop iteration tag (for)” is not just for simple iteration, it also provides various flexible options to make your list display more intelligent and diverse.
Handle empty data cleverly:{% empty %}温馨提示 of
Sometimes, the data list we obtain may be empty. In this case, if there is no prompt on the page, the user experience will be greatly reduced.forrepeatedly{% empty %}The clause is designed for this purpose:
{% for item in archives %}
<div class="item-display">{{ item.Title }}</div>
{% empty %}
<p>抱歉,目前没有找到相关内容。</p>
{% endfor %}
WhenarchivesThe loop continues as usual when the list is not empty; ifarchivesIf it is empty, then{% empty %}the content between them will be displayed, providing the user with a friendly feedback.
Customize the loop order:reversedandsortedMagic
You may wish to display the list data in a specific order.forLoop supportreversed(Reverse) andsorted(Sort) modifier:
reversed: Traverse the elements of the collection in reverse order. For example,{% for item in archives reversed %}.sortedUsed to sort lists of numbers or strings in ascending order. For example,{% for item in numbers sorted %}.
This allows you to easily control the display logic of content, such as the latest content at the top, or sorted by views from high to low.
Data alternates display:cycleThe color game of tags
When designing tables or lists, we often need to implement alternating row styles (such as different background colors).cycleTags can help you output preset values in order each time during the loop:
{% for item in archives %}
<div class="row-{% cycle 'odd' 'even' %}">
{{ item.Title }}
</div>
{% endfor %}
Each loop,cycleThey will output in turn'odd'and'even', adding visual hierarchy to your list.
Get loop information:forloop.Counterandforloop.Revcounter
Inside the loop, you can also access some special variables to get the state of the current loop:
forloop.Counter: indicates the number of iterations from1start counting.forloop.RevcounterThis indicates how many iterations are left until the loop ends, starting from总数Start counting down.
This is very useful when you need to number list items or apply specific styles based on position:
{% for article in archives %}
<div class="article-item {% if forloop.Counter == 1 %}featured{% endif %}">
<span>{{ forloop.Counter }}.</span>
<a href="{{ article.Link }}">{{ article.Title }}</a>
</div>
{% endfor %}
Here, we not only added a serial number to each article, but also added an extra one to the first articlefeaturedthe class name.
Actual case: Dynamic data list display
The 'loop iteration tag (for)' in Anqi CMS, combined with various content tags, can flexibly construct various dynamic lists.
Article list: the most common application scenario
In addition to the simple article list displayed above, we can also combine more article fields to build a richer list:
{% archiveList articles with type="page" limit="10" categoryId="1" %}
{% for item in articles %}
<div class="post-card">
{% if item.Thumb %}
<a href="{{ item.Link }}" class="post-thumbnail">
<img src="{{ item.Thumb }}" alt="{{ item.Title }}">
</a>
{% endif %}
<div class="post-content">
<h2 class="post-title"><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
<p class="post-excerpt">{{ item.Description|truncatechars:100 }}</p>
<div class="post-meta">
<span>发布于:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
<span>阅读量:{{ item.Views }}</span>
<span>分类:<a href="{% categoryDetail with name='Link' id=item.CategoryId %}">{% categoryDetail with name='Title' id=item.CategoryId %}</a></span>
</div>
</div>
</div>
{% empty %}
<p>此分类下暂无文章。</p>
{% endfor %}
{% endarchiveList %}
This example shows a list of articles containing thumbnails, titles, abstracts, publication time, reading volume, and categories. Among themarchiveListThe tag specifies the category ID to be retrieved as 1 and enables pagination mode.
Categories and navigation: Build multi-level menus.
For the website's category menu, we usually need to display a multi-level structure. This can be easily achieved by nesting usingcategoryListTags andforloop, it can be easily implemented:
{% categoryList mainCategories with moduleId="1" parentId="0" %}
<ul class="main-menu">
{% for mainCat in mainCategories %}
<li>
<a href="{{ mainCat.Link }}">{{ mainCat.Title }}</a>
{% if mainCat.HasChildren %}
<ul class="sub-menu">
{% categoryList subCategories with parentId=mainCat.Id %}
{% for subCat in subCategories %}
<li><a href="{{ subCat.Link }}">{{ subCat.Title }}</a></li>
{% endfor %}
{% endcategoryList %}
</ul>
{% endif %}
</li>
{% endfor %}
</ul>
{% endcategoryList %}
Here, the outer loop traverses the top-level categories, and the inner loop determines whether each top-level category has subcategories (mainCat.HasChildrenIf there are, retrieve and traverse the subcategories again to build a clear multi-level navigation structure.
Other dynamic data: friend links, banners, etc.
forThe versatility of the loop means it can be used for any data provided in a list form in the Secure CMS. For example, you can use it tolinkListTags andfordisplay links in a loop, or usebannerListTag display on homepage carousel:
`twig {# Friend link list #}
{% linkList links %}
{% for link in links %}
<a href