How to flexibly use in AnQiCMS templates{% for ... in ... %}Tag traversal data list?

As an experienced website operations expert, I fully understand the importance of an efficient and flexible template system for content management. AnQiCMS, as an enterprise-level content management system based on the Go language, has absorbed the essence of the Django template engine in template design, especially its powerful data traversal capability,{% for ... in ... %}Tags are one of the core tools for building dynamic web page content. Today, let's 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 also difficult to maintain.{% for ... in ... %}Loop tags are like magic, helping us automatically iterate and render data collections, greatly enhancing the reusability and maintenance efficiency of templates.

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

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

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

Here,collectionrepresent the data list or array you want to iterate over (for example, through)archiveList/categoryListtags to obtain the data set), anditemrepresents the data in each iteration,collectionthe current element. The code within the loop will targetcollectioneach of themitemonce, until all elements have been processed.

For example, if you want to display the titles and links of the 5 most recently published articles, 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,articlesthat is, througharchiveListthe article collection obtained by the tag, every loop,articleVariables will represent the various data of the current article, such as the title, link, and description, to dynamically generate content.

Gracefully handle empty lists:{% empty %}Block

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

AnQiCMS provides us with{% empty %}This block allows you to display alternate content when the dataset is empty, rather than a blank space.

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

Continuing with our example list in the above article,articlesThe list is empty, we can politely remind 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 %}

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

Deeply Control Loops: The Clever Use of Special Variables and Modifiers

{% for %}The power of tags is not only limited to iteration and handling empty lists, it also provides some built-in special variables and modifiers to make loop control more refined.

1. Loop counter:forloop.Counterandforloop.Revcounter

Sometimes we need to know how many times the loop has occurred, or how many more times are left.forloopThe object provides this information:

  • forloop.Counter: The current loop number, starting from 1.
  • forloop.RevcounterThis is 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

AnQiCMSforTags also provide convenient data processing capabilities, allowing sorting or reversing of data at the template level without additional backend operations.

  • reversedReverse the order of the data list.
  • sortedSort the data list (usually by ID or default sort field).

You can use them withfortags together:

{# 倒序显示文章列表 #}
{% 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. Alternating display content:cycletags

To achieve richer visual effects, such as zebra striping of table rows, or alternating layout of content areas,cycleTags are particularly practical. 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 in output.odd-rowandeven-row, to add alternating CSS classes to list items.

Practical Training: 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. Dynamically generated website navigation

The navigation menu usually has a multi-level structure,navListTag combination{% for %}It 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 demonstratesforThe use of loops in nesting, which can handle complex structures of multi-level navigation.

2. Display website categories and their subordinate documents.

Assume you want to display several main article categories on the homepage, and list the latest few 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 iterates over the articles under the current category ID.

3. Display friend links in bulk.

A simple friend links list can also be used by{% for %}Efficient Display