How to use a `for` loop to iterate over data and display content in AnQiCMS templates?

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.At this point, the 'for loop' has become the core tool for us to traverse these data and display it on the web page.Understand and masterforLoops will greatly enhance the flexibility and development efficiency of the template.

Core syntax: the cornerstone of iterating over data.

In AnQiCMS template,forThe syntax of the loop is concise and straightforward, it draws inspiration from the Django template engine style. The basic structure is to use{% for item in collection %}to start the loop, and{% endfor %}to end the loop. Here is thecollectionIt is the collection of data you want to iterate over, whileitemis a temporary variable name, representing the current element of the collection in each iteration.

For example, suppose we want to display the latest few articles. We can usearchiveListtags to get the article data, and thenforloop through them 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 assigns the list of articles obtainedarticlesto the variable, then{% for article in articles %}will sequentially assignarticleseach article object in it toarticlethe variable. Inside the loop, we can use{{ article.Title }}/{{ article.Link }}Access the various properties of the current article, such as title, link, description, and creation time.

Master loops flexibly: special variables and practical tips.

AnQiCMS'forLoops 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 the current iteration in a loop,forloop.CounterA variable comes into play. It returns the current loop index 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 sets. For example, we want to add a special 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 %}

Moreover, if your dataset may be empty, you do not want to display a blank area on the page, but instead show a friendly prompt, you can use{% empty %}a label. This label must follow immediately afterforAfter the loop,{% empty %}the content will only be displayed incollectionwhen 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: Traversal of common data types

Let's go through several practical scenarios to see how to effectively use AnQiCMS templates.forLoop through different types of data.

Loop through the article list.

As mentioned before, traversing the list of articles is one of the most common needs. We can combinearchiveListAll kinds of label parameters, such as obtaining different article collections by category ID, recommendation 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 a website navigation or category module, it is often necessary to traverse the website's category data.categoryListTags can help us obtain categories and support multi-level category retrieval.

{# 获取所有顶级分类(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>

Traverse the navigation menu

The website's navigation menu usually needs to be dynamically generated,navListtags can obtain the navigation data configured in the background. Since the navigation may have multiple levels, it can also be used hereforby means of nested loops.

{# 遍历主导航菜单 #}
<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: A Glance at Advanced Usage

AnQiCMS'forLoops also support some modifiers to achieve more complex traversal requirements:

  • reversed: AtforAdd after the tagreversedYou can reverse the traversal order. For example:{% for item in collection reversed %}.
  • sorted: If by default, ifcollectionis a sortable Go slice, plussortedit can be sorted. For example:{% for item in collection sorted %}.
  • cycle:cycleTags can be output alternately in each loop with predefined values, which is very useful for implementing zebra line effects or different class names in carousel slides. For example:{% cycle 'odd' 'even' as rowClass %}Combineclass="{{ rowClass }}".

Summary

forLoops are an indispensable tool for handling list data in the AnQiCMS template.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.


Frequently Asked Questions (FAQ)

  1. Question: How toforIn a loop, how do you get the current loop index (for example, to determine if it's the first or last item)?Answer: You can use special built-in variables.forloop.CounterGet the current loop index starting from 1, for example{% if forloop.Counter == 1 %}...{% endif %}. If you need to count backwards from the end of the list, you can useforloop.Revcounter.

  2. Ask: If the data set I traverse may be empty, how can I display a custom prompt instead of a blank page?Answer: In{% for ... %}and{% endfor %}Between labels, you can insert one{% empty %}label. When the data set is empty,{% empty %}The content within the tags will be rendered, replacing the empty loop result.

  3. **Question: How can I access the custom article in the loop?