In the Anqi CMS template, efficiently displaying list data is an indispensable part of website content operation.Whether it is displaying the latest articles, product lists, category directories, or customized data sets, flexibly iterating over these data and performing fine-grained control can greatly enhance the performance and user experience of the website.forThe loop tag feature is rich, not only supporting basic iteration, but also easily realizing counting, reversal, and more advanced operations.

Core Concepts:forBasic usage of loops

In the Anqi CMS template,forThe syntax of loops is very similar to the Django template engine, allowing users familiar with this syntax to quickly get started. Its basic structure is{% for item in collection %}...{% endfor %}Here,collectionRepresents the data collection you want to iterate over (for example, througharchiveList/categoryListtags obtained data), anditemrepresents the temporary variable for the current data item in each iteration.

For example, if you want to display a list of recently published articles, you would usually usearchiveListtags to get data, thenforloop through:

{% archiveList articles with type="list" limit="5" %}
    {% for article in articles %}
        <div class="article-item">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>{{ article.Description }}</p>
            <span>发布日期: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
        </div>
    {% endfor %}
{% endarchiveList %}

In this example,articlesis througharchiveListthe set of articles obtained,articleIt represents the current article object in each loop. You can name it whatever you like, as long as youarticlecan be replaced with any name that is easy to understand, as long as you keepforThe variable is used within the statement.

Useful tools in loops: counting and state

When traversing data in a loop, we often need to know which time the loop is currently or how many items are left. The Anqi CMS providesfora built-in variable for loopsforloopIt includes detailed information about the current loop state, among which the most commonly used isforloop.Counterandforloop.Revcounter.

  • forloop.CounterThis variable starts from 1 and increments with each loop, representing the current item number.This is very useful when you need to add numbers, rankings, or special treatment for the first and last items in a list.
  • forloop.Revcounter: AndCounterOn the contrary,RevcounterStarting from the total number of items in the list, it represents how many items (including the current item) are left until the end of the list. For example, if the list has 5 items,RevcounterIt is 5 in the first loop, 4 in the second, and so on until the last item is 1.

CombineifLogical judgment label, you can easily implement various conditional display effects. For example, add a special style to the first item in the list:

{% archiveList articles with type="list" limit="5" %}
    {% for article in articles %}
        <div class="article-item {% if forloop.Counter == 1 %}is-first{% endif %}">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>这是第 {{ forloop.Counter }} 篇文章,还剩下 {{ forloop.Revcounter - 1 }} 篇。</p>
        </div>
    {% endfor %}
{% endarchiveList %}

Passforloop.CounterYou can clearly know the progress of the current loop and adjust the presentation of content accordingly.

Flexible control of order: flip and sort

Sometimes, we may need to display list data in different orders, such as displaying the latest content in reverse order, or sorting by a certain attribute. Anqi CMS'sforLoops also provide concise modifiers:reversedandsorted.

  • reversed: This modifier simply traverses the data set in reverse order. If the data you retrieve from the database is in descending order by time but you want to display it in ascending order in the template, you can usereversed.
  • sorted: This modifier will perform a default sort on the data set (usually in the natural order of elements, such as numerical size or alphabetical order). Please note, sortedEnglish for: Usually used to sort simple collections.
  • Combined use:reversed sortedEnglish for: You can combine these two modifiers. In this case, the list will be sorted first, and then reversed.

The following usesreversedShow the article list in reverse order example:

{% archiveList articles with type="list" limit="5" %}
    {% for article in articles reversed %} {# 这里添加 reversed 翻转顺序 #}
        <div class="article-item">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>(倒序显示)发布日期: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</p>
        </div>
    {% endfor %}
{% endarchiveList %}

It is worth noting that,sortedModifiers may not sort complex object collections as you expect by default. For more complex sorting requirements, you may need to specify the sorting method when querying data from the backend, orforOutside the loop to perform data preprocessing.

Handling empty list:emptytags

When you try to iterate over a potentially empty list, you might worry about blank areas or errors appearing on the page. Safe CMS'sforloop provides aemptyLabel, used to display alternative content when the collection is empty, avoiding extraifJudgment, making the template code more concise:

{% archiveList articles with type="list" categoryId="999" %} {# 假设分类ID 999下没有文章 #}
    {% for article in articles %}
        <div class="article-item">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
        </div>
    {% empty %} {# 当 articles 集合为空时,显示以下内容 #}
        <p class="no-content">当前分类下暂无文章,敬请期待!</p>
    {% endfor %}
{% endarchiveList %}

So, even if there is no content under a category temporarily, your website can友好ly inform visitors instead of displaying a blank page.

Advanced Tips: Clean Output and Nested Loops

Remove empty lines with logic tags

During the template rendering process,forLoop orifThe judgment and logical tags may produce unnecessary blank lines in the final HTML output, affecting the neatness of the HTML code. Anqi CMS provides a trick to solve this problem: add a hyphen at the beginning or end of the tag-.

  • {%- for ... %}: Remove leading spaces before the tag.
  • {% endfor -%}: Remove trailing spaces after the tag.

This small change can make the generated HTML source code more compact:

<ul>
{%- archiveList articles with type="list" limit="3" %}
    {%- for article in articles %}
    <li>
        <a href="{{ article.Link }}">{{ article.Title }}</a>
    </li>
    {%- endfor %}
{%- endarchiveList %}
</ul>

Nested loops

For multi-level data structures, such as categories (level 1 list) containing articles (level 2 list), you can use nestedforcircular to display. The safety CMS'scategoryListandarchiveListLabels can be used together to achieve this effect:

[en]`twig {% categoryList categories with moduleId=“1” parentId=“0” %}

{% for category in categories %}
    <div class="category-section">
        <h2><a href="{{ category.Link }}">{{ category.Title }}</a></h2>
        <ul>
            {% archiveList articles with type="list" categoryId=category.Id limit