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

Calendar 👁️ 59

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?

Related articles

How to use the `if` tag for conditional judgment to control content display in AnQiCMS templates?

How to use the `if` tag for conditional judgment to control content display in AnQiCMS templates?When building website templates, we often need to display or hide specific content blocks based on different conditions.For example, the image will be displayed only when the article has a thumbnail, or the welcome message will be displayed only after the user logs in.In the AnQiCMS template system, the `if` tag is a powerful tool for implementing conditional judgments.It uses a syntax similar to the Django template engine, concise and expressive, making the content display logic clear and easy to understand

2025-11-08

How to dynamically retrieve and display the contact information of the website in AnQiCMS?

In today's digital age, a website's contact information is more than just cold numbers or addresses; it is a bridge for users to build trust and communicate with the company.Efficiently and accurately display this information on the website, and be able to update it flexibly as needed, which is crucial for any website operator.AnQiCMS as an enterprise-level content management system provides a very intuitive and powerful solution in this aspect, allowing you to easily manage these key information without touching complex code.This article will introduce how to configure and dynamically obtain the contact information of the website in AnQiCMS

2025-11-08

How to display the document list under a specific Tag in AnQiCMS?

In AnQiCMS, tags (Tag) are a powerful and flexible way to organize content, allowing you to associate documents in multiple dimensions without relying on traditional hierarchical classification structures.When you want to display all documents under a specific topic or keyword, it is particularly important to show the document list under a specific tag.This not only helps visitors find the content they are interested in faster, but also effectively improves the internal link structure and SEO performance of the website.

2025-11-08

How to retrieve and display the friend link list in AnQiCMS template?

In website operation, friendship links are an important factor in improving website authority, increasing external traffic, and optimizing user experience.AnQiCMS (AnQiCMS) is well aware of this, and therefore provides a convenient friend link management function in system design, and supports flexible calling and display in templates.This article will provide a detailed introduction on how to retrieve and display the friend link list in your AnQiCMS template.### Management of friendship links: Starting from the background Before starting the template call, make sure that your website's background has configured the friendship links

2025-11-08

How to format a timestamp (timestamp) into a readable date format for display in AnQiCMS?

In the process of website operation, the effective display time of content publishing or updating is crucial for improving user experience and the readability of content.If time information is presented in the original timestamp format, it is often difficult for ordinary users to understand.AnQiCMS provides a straightforward and flexible way to help you convert these digital timestamps into easily readable date and time formats.### How AnQiCMS handles timestamps AnQiCMS typically uses standard Unix Timestamp format for storing content time information

2025-11-08

How to truncate a string and add an ellipsis (...) to limit the display length in AnQiCMS template?

In AnQiCMS template development, we often need to refine the content displayed on the website, such as article titles, summaries, or abstracts of a text.If the content is too long, it not only affects the beauty of the page, but may also reduce the user's reading experience.AnQiCMS's powerful template engine provides a simple and efficient method to solve this problem, allowing us to easily extract strings and automatically add ellipses (...) to elegantly limit the display length of content.

2025-11-08

How to safely output HTML code in the template without escaping in AnQiCMS?

When using AnQiCMS for website template development or content display, you may encounter situations where you need to output HTML code directly on the page, only to find that the code is automatically escaped, for example, the `<p>` tag becomes `&lt;This often confuses those who are new to it.In fact, this is the default measure taken by the AnQiCMS template engine for website security.### Understanding the default security mechanism of AnQiCMS templates The AnQiCMS template engine design has drawn inspiration from

2025-11-08

How to automatically wrap long text to a specified length in AnQiCMS template?

In the presentation of website content, the way long texts are displayed is often a key factor affecting user experience and the beauty of the page.When we need to display a long text content, such as an article summary, product description, or detailed introduction, in a more readable and layout-adaptive way, AnQiCMS's template function provides a powerful and flexible solution.AnQiCMS uses syntax similar to Django template engine, with various built-in filters (Filters) that can help us easily format text.

2025-11-08