AnQiCMS with its flexible and powerful template system makes content display efficient and expressive.For website operators and developers, mastering how to iterate and display data in templates is a key step to unlocking their powerful features and bringing website content to life.forLoop, make your dynamic data easy to display.
AnQiCMS's template engine adopts syntax similar to Django, which allows users familiar with other mainstream template languages to quickly get started. In the template, when you need to display a series of data with the same structure, such as article lists, product categories, navigation menus, or image galleries, forThe loop is your powerful assistant.
The framework of the loop: basic syntax tutorial
forThe most basic form of a loop is to traverse a dataset (such as an array or list) and perform the same operation on each element. Its syntax is very intuitive:
{% for 变量名 in 集合 %}
{# 在这里放置你希望对每个元素执行的代码 #}
{{ 变量名.属性 }}
{% endfor %}
Here, 集合It is the dataset you want to iterate over, and变量名it represents the temporary name of the current element in each iteration. For example, if you have a list of articles namedarchivesyou can iterate over it like this:
{% archiveList archives with type="list" limit="5" %}
{% for article in archives %}
<div class="article-item">
<h2><a href="{{ article.Link }}">{{ article.Title }}</a></h2>
<p>{{ article.Description }}</p>
<span>发布日期:{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
</div>
{% endfor %}
{% endarchiveList %}
This code will extract fromarchivesextract article data one by one from the collection, and display the current article's title, link, description, and publication date in each iteration.
Handle empty list:{% empty %}usefulness
Sometimes, the data set you iterate over may be empty. If displayed directly, the page may appear blank. AnQiCMSforprovided a loop{% empty %}The clause allows you to handle this situation gracefully:
{% archiveList recentPosts with type="list" limit="3" %}
{% for post in recentPosts %}
<div class="post-card">
<h3><a href="{{ post.Link }}">{{ post.Title }}</a></h3>
</div>
{% empty %}
<p>暂时没有最新文章发布。</p>
{% endfor %}
{% endarchiveList %}
IfrecentPostsThere is data in the collection, it will normally display the article card; if not, it will display the prompt "There are no latest articles published yet." to avoid the page looking empty.
Enhance loop function: Sorting and reverse
AnQiCMS'forThe loop also supports some practical modifiers to allow you to more flexibly control the display order of data. You can addfora label directly afterreversedReverse iterate or usesortedSort the data (if the elements of the collection are of sortable numeric types):
{# 倒序显示文章列表 #}
{% archiveList latestNews with type="list" limit="5" %}
{% for news in latestNews reversed %}
<div class="news-item">{{ news.Title }}</div>
{% endfor %}
{% endarchiveList %}
{# 假设有一个数字列表`numberList`,对其进行排序 #}
{% for num in numberList sorted %}
<span>{{ num }}</span>
{% endfor %}
These modifiers can help you easily adjust the display of data on the front end without changing the original data acquisition logic.
Insight into loop progress:forloopPractical properties of objects
InforInside the loop, you can still access a specialforloopobject that provides various useful information about the current loop state. The most commonly used are:
forloop.Counter: The current iteration number of the loop, starting from 1.forloop.Revcounter: The remaining iteration number of the loop.forloop.First: If the current element is the first in the loop, thentrue.forloop.Last: If it is the last element in the loop, thentrue.
Using these properties, you can add unique styles or behaviors to specific elements in the list:
{% archiveList products with type="list" limit="4" %}
{% for product in products %}
<div class="product-card {% if forloop.First %}first-item{% endif %} {% if forloop.Last %}last-item{% endif %}">
<h3>{{ forloop.Counter }}. {{ product.Title }}</h3>
<img src="{{ product.Thumb }}" alt="{{ product.Title }}">
</div>
{% endfor %}
{% endarchiveList %}
In this example, the first product card will be addedfirst-itemclass, the last one will be addedlast-itemclass, and each product will display its number in the list.
Creative display:{% cycle %}Tag
{% cycle %}The tag allows you to output different values in a loop. This is very useful for implementing zebra line effects (different background colors for odd and even rows), different animation classes in sliders, and other scenarios:
{% archiveList items with type="list" limit="6" %}
{% for item in items %}
<div class="item-row {% cycle 'bg-light' 'bg-dark' %}">
<p>{{ item.Title }}</p>
</div>
{% endfor %}
{% endarchiveList %}
Each loop,item-rowalternates to obtainbg-lightandbg-darkclass, thus easily achieving a visual alternating effect.
Practical exercise: Application of for loop in common scenarios
After understanding the basic and advanced usage, let's take a look at some common loop application scenarios in AnQiCMS.for。“
1. Dynamic navigation menu
A typical website usually has multi-level navigation,forLoops handle this nested structure well.navListTags can retrieve navigation data, by判断item.NavListDoes it exist to implement the rendering of secondary even multi-level menus.
<nav>
<ul>
{% navList mainNav with typeId=1 %}
{% for item in mainNav %}
<li {% if item.IsCurrent %}class="active"{% endif %}>
<a href="{{ item.Link }}">{{ item.Title }}</a>
{% if item.NavList %} {# 如果有子导航 #}
<ul class="submenu">
{% for subItem in item.NavList %}
<li {% if subItem.IsCurrent %}class="active"{% endif %}>
<a href="{{ subItem.Link }}">{{ subItem.Title }}</a>
</li>
{% endfor %}
</ul>
{% endif %}
</li>
{% endfor %}
{% endnavList %}
</ul>
</nav>
Here we use an outer layerforLoop to handle the first-level navigation, and then use an inner layerforLoop to handle the secondary navigation.item.IsCurrentCan help you determine if the current link is selected, convenient for adding highlight styles.
2. Article/Product List Display
Whether it is the hot articles on the homepage or the product list on the category page,forLoops are at the core. CombinedarchiveListTags, you can easily display dynamic lists containing images, descriptions, and dates.
<div class="article-list">
{% archiveList articles with type="list" moduleId="1" limit="10" order="views desc" %}
{% for article in articles %}
<article>
{% if article.Thumb %}
<a href="{{ article.Link }}"><img src="{{ article.Thumb }}" alt="{{ article.Title }}"></a>
{% endif %}
<h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
<p>{{ article.Description|truncatechars:100 }}</p>
<div class="meta">
<span>{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
<span>阅读量:{{ article.Views }}</span>
</div>
</article>
{% empty %}
<p>很抱歉,当前没有找到相关内容。</p>
{% endfor %}
{% endarchiveList %}
</div>
Here we obtained the 10 most viewed articles, and we utilizearticle.ThumbCheck if there is a thumbnail,article.Description|truncatechars:100Truncate the description.
3. Display a group of images or an attachment list
On the article or product detail page, if the content model includes image galleries or attachment fields, they are usually stored in list form. You can directly iterate over these fields to display them.
`twig {# Assuming archive.Images is an array of image URLs #}
{% archiveDetail currentImages with name="Images" %}
{% if currentImages %}
{% for imageUrl in currentImages %}
<a href="{{ imageUrl }}" data-lightbox="gallery">
<img src="{{ imageUrl }}" alt="图片展示">
</a>
{% end