During the template development process of AnQi CMS, dynamic data display is one of the core requirements.Whether it is an article list, product display, or navigation menu, we cannot do without traversing array or collection data.And in this process, how to elegantly handle the case of empty data, ensuring the beauty of the page and user experience is equally important.
The AnQi CMS template engine supports powerful features similar to Django template syntax, includingforThe loop is a powerful tool for processing data lists. It also provides a very practical{% empty %}The label is specifically used to handle the scenario where the data collection is empty, making our template code more concise and robust.
UnderstandingforBasic usage of loops
In the Anqi CMS template,forThe syntax of loops is very intuitive, allowing us to access each element of a data collection one by one. Typically, you will see such a structure:
{% for item in collection %}
{# 在这里使用 item 来访问集合中的每个元素属性 #}
{% endfor %}
here,collectionrepresent the data array or list you want to iterate over, anditemIt is the temporary variable for each iteration of the current element in the loop. For example, when you need to display the latest list of articles, you can call it like thisarchiveListTag to get data, then useforLoop through:
{% archiveList latestArticles with type="list" limit="5" %}
{% for article in latestArticles %}
<div class="article-summary">
<h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
<p>{{ article.Description|truncatechars:100 }}</p>
<small>发布日期: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</small>
</div>
{% endfor %}
{% endarchiveList %}
In this example,latestArticlesIt is an array that contains multiple articles,articlewhich represents the current article in each loop, you can directly access its properties througharticle.Title/article.Linkand so on.
Furthermore,forLoops also provide some useful built-in variables, such asforloop.CounterYou can get the current number of times the loop runs (starting from 1),forloop.RevcounterIt can obtain the number of remaining elements, which is very convenient when adding special styles to elements at specific positions.
Gracefully handle empty arrays:{% empty %}Tag
In practical applications, a dataset may become an empty array due to various reasons (such as no content published, empty filtering results, etc.). If you only use the above mentionedforA loop, when the collection is empty, no content will be displayed on the page, which may cause the page layout to appear blank, even confusing the user.
To solve this problem, the Anqi CMS template engine introduced{% empty %}a tag. This tag is specifically used withforlooping, whenforthe loop tries to traverse thecollectionis empty,forThe content inside the loop will be skipped and executed instead{% empty %}The content inside the tag. This allows you to display a friendly prompt or alternative content when there is no data.
Its basic syntax is as follows:
{% for item in collection %}
{# 正常遍历时显示的内容 #}
{% empty %}
{# 当 collection 为空时显示的内容 #}
{% endfor %}
Compared with the traditional way of first usingifThe statement to determine the length of the collection, and then decide whether to proceedforLoop,{% empty %}The style is undoubtedly more concise and semantically meaningful. For example, if the above list of articles may be empty, we can improve it like this:
{% archiveList latestArticles with type="list" limit="5" %}
{% for article in latestArticles %}
<div class="article-summary">
<h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
<p>{{ article.Description|truncatechars:100 }}</p>
<small>发布日期: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</small>
</div>
{% empty %}
<div class="no-content-message">
<p>抱歉,目前没有最新的文章可供展示。</p>
<p>您可以查看其他分类或稍后再回来!</p>
</div>
{% endfor %}
{% endarchiveList %}
By adding{% empty %}a block whenlatestArticlesWhen there are no articles, users will not see an empty area, but will see the prompt
More practical scenarios
{% empty %}Tags are not only suitable for article lists, but also can be very useful in any scenario that requires traversing arrays in Anqi CMS templates.
For example, when building website navigation, if there are no sub-navigations under a certain category, you can{% empty %}to control the display style:
{% navList mainNavigation %}
<ul class="header-nav">
{% for navItem in mainNavigation %}
<li>
<a href="{{ navItem.Link }}">{{ navItem.Title }}</a>
{% if navItem.NavList %} {# 检查是否有二级导航 #}
<ul class="sub-nav">
{% for subNavItem in navItem.NavList %}
<li><a href="{{ subNavItem.Link }}">{{ subNavItem.Title }}</a></li>
{% empty %}
{# 如果某个一级导航下没有二级导航,这里可以留空或显示其他内容 #}
{% endfor %}
</ul>
{% endif %}
</li>
{% empty %}
<p>网站导航配置中...</p>
{% endfor %}
</ul>
{% endnavList %}
For example, when you need to display the custom parameters of a document, these parameters are also returned in array form. If the document has not set any custom parameters,{% empty %}they can be used:
{% archiveParams docParams with sorted=true %}
<div class="document-parameters">
<h4>文档属性</h4>
{% for param in docParams %}
<p><strong>{{ param.Name }}:</strong> {{ param.Value }}</p>
{% empty %}
<p>此文档未设置任何额外的自定义属性。</p>
{% endfor %}
</div>
{% endarchiveParams %}
In practical development, use flexiblyforloop and{% empty %}The label can help us build a more flexible, user-friendly Anqi CMS website template.Always consider the scenario where data is empty and prepare in advance, which is an indispensable practice in template development.
Frequently Asked Questions (FAQ)
1.forCan loops be nested?
Yes,forLoops fully support nesting. For example, when building multi-level classification navigation, you can in aforUse another inside the loopforLoop to traverse subcategories, as shown in the navigation menu example in the article. However, it is recommended not to nest too deeply to avoid affecting the readability and performance of the template.
2. Besides{% empty %}Label, are there other methods to determine if an array is empty and display alternative content?
Of course there are. Although{% empty %}It is the simplest and recommended way to handle empty arrays in Anqi CMS templates, but you can also use traditionalifstatements to combine|lengthfilters to determine the length of an array. For example:
{% if collection|length > 0 %}
{% for item in collection %}
{# 遍历内容 #}
{% endfor %}
{% else %}
<p>没有数据可显示。</p>
{% endif %}
This method is also effective, but relatively speaking,{% empty %}more semantically meaningful, and the code is also more concise.
3. InforHow do I get the current index of a loop (for example, to determine if it's the first or last element)?
InforInside the loop, you can use a specialforloopvariable to get this information:
forloop.Counter: The current loop count (starting from 1).forloop.Counter0: The current loop count (starting from 0).forloop.Revcounter: The remaining loop count (counting down from the total).forloop.Revcounter0: The remaining number of iterations (counting down from the total, starting from 0).forloop.First: Boolean value, if it is the first iteration, thentrue.forloop.LastBoolean value, if it is the last loop iteration, thentrue.
For example, you can judge like this: “`twig {% for item in collection