How to use `for` loop to traverse data and display content in AnQiCMS template?

In AnQiCMS template development, we often need to display a series of dynamic content, such as the latest article list, product categories, navigation menu items, and even custom parameters.This is when the 'for loop' becomes the core tool for us to iterate through these data and display it on the webpage.forLoops will greatly enhance the flexibility and development efficiency of the template.

Core Grammar: The Foundation for Traversing Data

In AnQiCMS templates,forthe loop syntax is concise and intuitive, drawing inspiration from the Django template engine. The basic structure is to use{% for item in collection %}Start the loop, and{% endfor %}end the loop. This iscollectionis the collection of data you want to iterate over, anditemis a temporary variable name, representing the current element in the collection during each iteration.

For example, suppose we want to display the latest few articles. We can usearchiveListtags to get the article data, and then throughforloop to display one by one:

{% archiveList articles with type="list" limit="5" %}
    {% for article in articles %}
        <div class="news-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,archiveListThe tag will assign the article list obtainedarticlesto the variable, then{% for article in articles %}successively assignarticleseach article object in it toarticlethe variable. Inside the loop, we can use{{ article.Title }}/{{ article.Link }}Access various properties of the current article, such as title, link, description, and creation time.

Master loops flexibly: special variables and practical tips

AnQiCMSforLoops are not limited to simply traversing data; they also provide some special built-in variables and syntax structures to help us better control the logic and display effects of loops.

When we need to know which iteration we are on within a loop,forloop.CounterVariables come into play. It returns the current loop's index value starting from 1. If you need to count from the end of the list,forloop.RevcounterIt will return the index starting from 1 in reverse order of the total number of the set. For example, we want to add a special style class to the first article item:

{% archiveList articles with type="list" limit="5" %}
    {% for article in articles %}
        <div class="news-item {% if forloop.Counter == 1 %}featured-article{% endif %}">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>当前第{{ forloop.Counter }}篇,总共剩余{{ forloop.Revcounter }}篇未展示。</p>
        </div>
    {% endfor %}
{% endarchiveList %}

Also, if your data set may be empty, you do not want to show an empty area on the page instead, you can display a friendly prompt message, you can use{% empty %}a label. This label must followforAfter the loop,{% empty %}the content inside will only be displayedcollectionwhen it is empty.

{% archiveList articles with type="list" categoryId="10" limit="5" %}
    {% for article in articles %}
        <div class="product-card">
            <h4>{{ article.Title }}</h4>
            <img src="{{ article.Thumb }}" alt="{{ article.Title }}">
        </div>
    {% empty %}
        <p>当前分类下还没有任何产品哦,敬请期待!</p>
    {% endfor %}
{% endarchiveList %}

Practical Exercise: Traversing Common Data Types

Let us look at several actual scenarios to see how to effectively use AnQiCMS templates.forLoop through different types of data.

Loop through the article list.

As mentioned earlier, iterating over a list of articles is one of the most common needs. We can combinearchiveListTags and various parameters, such as getting different article collections by category ID, recommended attributes, or sorting method, and then displaying them.

{# 假设我们想展示置顶推荐(flag="f")的文章,并按发布时间倒序排列 #}
<div class="featured-articles">
    <h2>特别推荐</h2>
    {% archiveList topArticles with type="list" flag="f" order="id desc" limit="3" %}
        {% for item in topArticles %}
            <div class="card">
                <img src="{{ item.Logo }}" alt="{{ item.Title }}">
                <h4><a href="{{ item.Link }}">{{ item.Title }}</a></h4>
                <p>{{ item.Description|truncatechars:80 }}</p>
                <span>阅读量: {{ item.Views }}</span>
            </div>
        {% endfor %}
    {% empty %}
        <p>暂无推荐文章。</p>
    {% endarchiveList %}
</div>

Traverse the category list

When building website navigation or classification modules, it is often necessary to traverse the website's classification data.categoryListTags can help us get the classification and support the acquisition of multi-level classifications.

{# 获取所有顶级分类(parentId="0"),并展示其名称和链接 #}
<ul class="main-categories">
    {% categoryList categories with moduleId="1" parentId="0" %}
        {% for category in categories %}
            <li>
                <a href="{{ category.Link }}">{{ category.Title }}</a>
                {# 如果当前分类有子分类,我们可以进一步嵌套循环展示 #}
                {% if category.HasChildren %}
                    <ul class="sub-categories">
                        {% categoryList subCategories with parentId=category.Id %}
                            {% for subCategory in subCategories %}
                                <li><a href="{{ subCategory.Link }}">{{ subCategory.Title }}</a></li>
                            {% endfor %}
                        {% endcategoryList %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    {% endcategoryList %}
</ul>

Traversing the navigation menu

The website's navigation menu usually needs to be dynamically generated,navListtags can obtain the navigation data configured by the backend. Since the navigation may have multiple levels,fornested loops can be used to handle it.

{# 遍历主导航菜单 #}
<nav class="main-nav">
    <ul>
        {% navList mainNavs with typeId=1 %} {# 假设 typeId=1 是主导航的ID #}
            {% for navItem in mainNavs %}
                <li class="{% if navItem.IsCurrent %}active{% endif %}">
                    <a href="{{ navItem.Link }}">{{ navItem.Title }}</a>
                    {% if navItem.NavList %} {# 如果有子导航 #}
                        <ul class="sub-nav">
                            {% for subNavItem in navItem.NavList %}
                                <li class="{% if subNavItem.IsCurrent %}active{% endif %}">
                                    <a href="{{ subNavItem.Link }}">{{ subNavItem.Title }}</a>
                                </li>
                            {% endfor %}
                        </ul>
                    {% endif %}
                </li>
            {% endfor %}
        {% endnavList %}
    </ul>
</nav>

Further Exploration: A Glimpse into Advanced Usage

AnQiCMSforLoops also support some modifiers to achieve more complex iteration needs:

  • reversedOn:forAfter the label:reversedIt can reverse the iteration order. For example:{% for item in collection reversed %}.
  • sortedBy default, ifcollectionis a sortable Go slice, you can sort it. For example:sortedcan be sorted.{% for item in collection sorted %}.
  • cycle:cycleTags can be cycled through预设的 values in each loop, which is very useful for implementing zebra line effects or different class names in sliders. For example:{% cycle 'odd' 'even' as rowClass %}Combineclass="{{ rowClass }}".

Summary

forLoops are an indispensable tool for handling list data in AnQiCMS templates.By it, we can easily traverse various information such as articles, categories, navigation, and combine loop variables and conditional judgments to achieve diverse content display.Mastering these basic usages will help you build and maintain AnQiCMS website templates more efficiently and flexibly.


Common Questions (FAQ)

  1. Question: How toforRetrieve the current loop index within the loop (e.g., determine if it is the first item or the last item)?Answer: You can use special built-in variablesforloop.CounterGet the current loop index starting from 1, for example{% if forloop.Counter == 1 %}...{% endif %}To count backwards from the end of the list, you can useforloop.Revcounter.

  2. Ask: If the data collection I traverse may be empty, how can I display a custom prompt message instead of an empty page?Answer: In{% for ... %}and{% endfor %}between tags, you can insert a{% empty %}Tag. When the data set is empty,{% empty %}the content inside the tag will be rendered, replacing the empty loop result.

  3. **Q: How do I access a custom field of an article within the loop?