How to use the `{% for ... in ... %}` tag in AnQiCMS templates to iterate over a data list?

Calendar 👁️ 63

How to flexibly use Anqi CMS template{% for ... in ... %}How to traverse data list with tags

As an experienced website operations expert, I am well aware of the importance of an efficient and flexible template system for content management. AnQiCMS, as an enterprise-level content management system based on Go language, draws on the essence of the Django template engine in template design, especially its powerful data traversal capabilities, particularly{% for ... in ... %}Tags are one of the core tools for building dynamic web page content. Today, we will delve into how to make full use of this tag to make your website content more vivid and efficient.

In the daily work of content operation, we often need to display a series of data on the website, such as the latest article list, popular product recommendations, website classification navigation, or friendship links, etc.It is obviously not advisable to add these contents manually one by one, and it is difficult to maintain. At this point,{% for ... in ... %}Loop tags are like magic, enabling us to automatically iterate and render data collections, greatly enhancing the reusability and maintenance efficiency of templates.

Understanding{% for ... in ... %}structure

The AnQiCMS template tag syntax is very intuitive. When you need to iterate over a data list, the basic structure is like this:

{% for item in collection %}
    {# 在这里处理当前 item 的数据 #}
{% endfor %}

Here, collectionrepresent the list or array of data you want to iterate through (for example, througharchiveList/categoryListtags obtained from the data set), anditemrepresents what is represented in each iteration,collectionThe current element. The code within the loop will targetcollectioneachitemonce, until all elements have been processed.

For example, if you want to display the titles and links of the 5 latest articles published, you can organize your template in this way:

{% 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>
        </div>
    {% endfor %}
{% endarchiveList %}

In the above example,articlesIt is througharchiveListthe collection of articles obtained by the tag, each time the loop,articleVariables will represent various data items of the current article, such as title, link, and description, thereby dynamically generating content.

Gracefully handle empty lists:{% empty %}block

In practical applications, data lists are not always filled. For example, there may be no articles under a certain category, or the friend links have not been added yet. If you simply use{% for %}Label, when the list is empty, no content will be displayed on the page, which may confuse the user.

AnQiCMS provided for us{% empty %}A block to elegantly handle this situation. This block allows you to display a fallback content when the data set is empty instead of a blank.

{% for item in collection %}
    {# 列表不为空时显示的内容 #}
{% empty %}
    <p>抱歉,目前没有相关内容可供显示。</p>
{% endfor %}

Continuing with our article example, ifarticlesThe list is empty, we can kindly prompt the user:

{% 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>
        </div>
    {% empty %}
        <p>暂时没有最新文章发布,敬请期待!</p>
    {% endfor %}
{% endarchiveList %}

In this way, even if there is no data in the database, your website page can maintain a friendly user experience.

Deeply controlling loops: The clever use of special variables and modifiers

{% for %}The power of labels is not limited to traversal and empty list processing, it also provides some built-in special variables and modifiers to make loop control more fine-grained.

1. Loop counter:forloop.Counterandforloop.Revcounter

Sometimes we need to know which loop we are currently on, or how many loops are left.forloopThe object provides this information:

  • forloop.Counter: The current loop iteration number, starting from 1.
  • forloop.Revcounter: The remaining count of the current loop, counting backwards.

This is very useful when you need to add special styles to the first or last element of a list, for example:

{% categoryList categories with moduleId="1" parentId="0" %}
    <ul>
    {% for category in categories %}
        <li {% if forloop.Counter == 1 %}class="first-category"{% endif %}>
            <a href="{{ category.Link }}">{{ category.Title }} (第{{ forloop.Counter }}个,剩余{{ forloop.Revcounter }}个)</a>
        </li>
    {% endfor %}
    </ul>
{% endcategoryList %}

2. Data sorting and reversal:reversedandsorted

AnQiCMS'forThe tag also provides convenient data processing capabilities, without the need for additional backend operations, allowing for sorting or reversing data at the template level.

  • reversed: Traverse the data list in reverse order.
  • sorted: Sort the data list (usually by ID or default sort field).

You can use them withfortags:

{# 倒序显示文章列表 #}
{% archiveList articles with type="list" limit="5" %}
    {% for article in articles reversed %}
        <div class="article-item-reversed">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
        </div>
    {% endfor %}
{% endarchiveList %}

{# 排序后显示文章列表 #}
{% archiveList articles with type="list" limit="5" %}
    {% for article in articles sorted %}
        <div class="article-item-sorted">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
        </div>
    {% endfor %}
{% endarchiveList %}

3. Alternate content display:cycleTag

To achieve richer visual effects, such as the zebra strip effect of table rows, or the alternating layout of content areas,cycleLabels are particularly useful. They can cycle through a series of predefined values.

{% for item in list %}
    <div class="{% cycle 'odd-row' 'even-row' %}">
        {# 内容 #}
    </div>
{% endfor %}

here,cycleThey will alternate.odd-rowandeven-rowIt adds alternating CSS classes to list items.

Practice session: flexible application in common scenarios

Having mastered the basics, let's see how to use it in AnQiCMS{% for %}Apply tags to more practical scenarios:

1. Dynamic website navigation generation

Navigation menus usually have multi-level structures,navListLabel combination{% for %}Can be easily built:

{% navList navItems %}
    <ul class="main-nav">
    {% for item in navItems %}
        <li class="{% if item.IsCurrent %}active{% endif %}">
            <a href="{{ item.Link }}">{{ item.Title }}</a>
            {% if item.NavList %} {# 判断是否有子导航 #}
                <ul class="sub-nav">
                {% for subItem in item.NavList %} {# 嵌套循环子导航 #}
                    <li class="{% if subItem.IsCurrent %}active{% endif %}">
                        <a href="{{ subItem.Link }}">{{ subItem.Title }}</a>
                    </li>
                {% endfor %}
                </ul>
            {% endif %}
        </li>
    {% endfor %}
    </ul>
{% endnavList %}

This example perfectly demonstratesforUsing nested loops, which can handle the complex structures of multi-level navigation.

2. Display the website categories and their subordinate documents

Suppose you want to display several main article categories on the homepage, and list the latest several articles under each category:

{% categoryList categories with moduleId="1" parentId="0" limit="3" %}
    {% for category in categories %}
        <section class="category-block">
            <h2><a href="{{ category.Link }}">{{ category.Title }}</a></h2>
            <ul class="article-list">
                {% archiveList articlesInCategory with type="list" categoryId=category.Id limit="5" %}
                    {% for article in articlesInCategory %}
                        <li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
                    {% empty %}
                        <li>此分类下暂无文章。</li>
                    {% endfor %}
                {% endarchiveList %}
            </ul>
        </section>
    {% endfor %}
{% endcategoryList %}

Here, the outer loop iterates over categories, and the inner loop then iterates over the articles under the current category ID.

3. Display friendship links in bulk

A simple friendship links list can also be used through{% for %}Efficient display

Related articles

How to get the accurate length of strings, arrays, or key-value pairs in AnQi CMS templates?

In website content management, we often need to finely control the displayed data, such as limiting the number of characters in article titles, checking if the image collection is empty, or counting how many entries are in a list.As an experienced website operations expert, I know how AnQiCMS' powerful and flexible template engine can help us meet these needs.

2025-11-06

What does the `get_digit` filter return when it encounters a non-existent position?

AnQiCMS (AnQiCMS) leverages the efficient characteristics and flexible template engine of the Go language to provide strong support for content management.During template development, we often use various filters to format and process data.Among them, the `get_digit` filter is a utility used to extract a specific digit from a number.Then, how will it respond when we use it to extract a digit from a number at a position that actually does not exist?Let's delve deeper into it.

2025-11-06

How to accurately extract a specified digit from a number in Anqi CMS template?

In the template world of AnQi CMS, efficiently and flexibly handling data is the key to website operators improving the expression of content.As an experienced website operations expert, I know the power of template language lies in its ability to transform complex technical logic into simple and practical content presentation.Today, we will focus on a seemingly simple but extremely practical need: how to accurately extract the digit you want from a number in the Anqi CMS template.

2025-11-06

What is the actual difference between the `default` and `default_if_none` filters when handling variable default values?

In the AnQi CMS template world, we often encounter situations where variables may not have values.For example, the nickname of the user may be empty, the introduction of the article may not be filled in, or a certain configuration item may not exist at all.At this time, in order to make the page display more friendly and information more complete, we need to set up a 'backup' for these variables - that is, the default value.

2025-11-06

How to get the index starting from 1 in the current iteration of the `for` loop?

## How to skillfully use AnQiCMS template to easily get the "first" and "Nth" indices in the loop In website content operation, we often need to display a series of contents on the page, such as article lists, product displays, navigation menus, etc.In order to better present the content, we often need to fine-tune the control of each item in the list, such as adding special styles to the first item, or displaying the item's serial number in the list.

2025-11-06

How to get the remaining number of items in the current iteration of the `for` loop (reverse index)?

As an experienced website operations expert, I know that the template function of the content management system is the core of flexible and diverse content display on the website.AnQiCMS (AnQi CMS) leverages the efficient features of the Go language and the Django-like template syntax, providing us with powerful content operation support.Today, let's delve deeply into a practical skill often encountered in template development: how to elegantly obtain the remaining items of the current iteration in the `for` loop, which is what we often call the 'reverse index'.

2025-11-06

How to elegantly display a 'no content' prompt when using the `empty` tag in AnQiCMS `for` loop?

In the daily operation of the website, we understand that the way content is presented is crucial to user experience.A well-designed website that not only provides rich information but also gives users friendly prompts when content is missing, avoiding the embarrassment of blank pages or error messages.

2025-11-06

How does the `{% for ... in ... reversed %}` tag implement reverse traversal of a data list?

As an experienced website operations expert, I am well aware of the importance of content presentation for user experience and information delivery.In AnQiCMS (AnQiCMS) such an efficient and flexible content management system, mastering its powerful template tag functions is the key to our refined content operation.Today, let's delve into a seemingly simple yet extremely practical template tag modifier——`{% for ...in ...reversed %}`, see how it plays a role in the reverse traversal of the data list.

2025-11-06