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