How to use a for loop to iterate over a data list in AnQiCMS template?

Calendar 👁️ 70

Master AnQiCMS template: useforThe art of looping through data lists

Hello everyone, partners of AnQiCMS operation

In daily website content operation, we often need to display a series of data, whether it is the latest article list, product classification navigation, or comment details, it is inseparable from the traversal and display of the data set.AnQiCMS as an efficient and flexible content management system, understands the importance of templates in content presentation.Today, let's delve deeply into a core and powerful tag of the AnQiCMS template engine -forLoop and see how to easily handle various data lists to enliven your website content.

AnQiCMS's template engine adopts a syntax style similar to Django, which makes it very quick for partners with other web development experience to get started, and even for beginners, its intuitiveness allows you to quickly master it.forThe loop is the basis for constructing dynamic content display, it can help us present the data obtained from the backend in a structured and customizable way on the front end.

forThe core usage of loops: traversing data sets

Imagine that you have obtained a set of article data from the background, and now you need to display these articles one by one on the web page. At this time,forLoops come into play. Their basic syntax is very concise and clear:

{% for item in collection %}
    {# 在这里放置你希望对每个“item”进行的操作和显示逻辑 #}
{% endfor %}

Here, collectionRepresents the data set you want to iterate over, for example, AnQiCMS'sarchiveList(Article list),categoryListData obtained from tags such as (category list) anditemis a temporary variable that representscollectionan item in one. By accessingitemthe different properties (such asitem.TitleGet the title,item.LinkGet the link, and we can display the detailed information of each data item.

Let's take a look at several common data lists to see.forThe charm of loops.

Example 1: Dynamically display the article list.

The article list is one of the most common content forms on a website. Suppose we usearchiveListtags to get the latest articles:

{% archiveList articles with type="list" limit="10" %}
    <div class="article-list">
    {% for article in articles %}
        <article class="article-item">
            <a href="{{ article.Link }}" title="{{ article.Title }}">
                <h3>{{ article.Title }}</h3>
                <p>{{ article.Description }}</p>
                <div class="meta-info">
                    <span>发布时间:{{ stampToDate(article.CreatedTime, "2006年01月02日") }}</span>
                    <span>阅读量:{{ article.Views }}</span>
                </div>
            </a>
        </article>
    {% endfor %}
    </div>
{% endarchiveList %}

In this example, we first go througharchiveListtags to store the data toarticlesIn the variable, and limit it to only display 10 list items. Next,{% for article in articles %}It will iterate over these 10 articles one by one inside the loop.article.Link/article.Title/article.Descriptionandarticle.ViewsProperties will respectively display the link, title, introduction, and views of the article. Particularly, for the timestamp fieldCreatedTimeWe rely on the built-in AnQiCMS.stampToDateThe function is formatted to display in a more friendly "2006-01-02" format.

It is worth mentioning that ifarticlesThis collection is empty, we do not want to show blank on the page, but we can give users a friendly prompt. AnQiCMS'sforprovided a loopemptyblock to elegantly handle this situation:

{% archiveList articles with type="list" limit="10" %}
    <div class="article-list">
    {% for article in articles %}
        <article class="article-item">
            <a href="{{ article.Link }}" title="{{ article.Title }}">
                <h3>{{ article.Title }}</h3>
                <p>{{ article.Description }}</p>
            </a>
        </article>
    {% empty %}
        <p>抱歉,目前还没有任何文章发布。</p>
    {% endfor %}
    </div>
{% endarchiveList %}

Whenarticlesis empty,{% empty %}The content within will be rendered, providing a better experience for users.

Example two: Build multi-level category navigation

Website navigation usually needs to display categories, even subcategories.forThe loop can also handle this nested iteration requirement.

<nav class="main-nav">
    <ul>
    {% navList mainMenu with typeId=1 %} {# 获取ID为1的主导航数据 #}
        {% for mainItem in mainMenu %}
            <li {% if mainItem.IsCurrent %}class="active"{% endif %}>
                <a href="{{ mainItem.Link }}">{{ mainItem.Title }}</a>
                {% if mainItem.NavList %} {# 如果有子导航,则进行嵌套循环 #}
                    <ul class="sub-nav">
                    {% for subItem in mainItem.NavList %}
                        <li {% if subItem.IsCurrent %}class="active"{% endif %}>
                            <a href="{{ subItem.Link }}">{{ subItem.Title }}</a>
                        </li>
                    {% endfor %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
    {% endnavList %}
    </ul>
</nav>

Here, we first go throughnavListGet the main navigation data tomainMenuVariable. OuterforLoop through the main navigation items, and throughmainItem.NavListCheck if there is a sub-navigation. If it exists, use it again in the inner layer.forLoop through the sub-navigation items.mainItem.IsCurrentandsubItem.IsCurrentSuch properties can help us determine whether the current navigation item is selected, thereby addingactivestyles to enhance the user experience.

Example three: Show custom document parameters

In AnQiCMS, you can customize various parameters for articles or product models, such as "author", "source", "product model", etc., and also throughforcyclic unified display.

<div class="product-specs">
    <h4>产品参数</h4>
    {% archiveParams specs with id=archive.Id %} {# 获取当前文档的所有自定义参数 #}
        <ul>
        {% for param in specs %}
            <li>
                <span>{{ param.Name }}:</span>
                <span>{{ param.Value | safe }}</span> {# 注意:如果param.Value可能包含HTML,请使用|safe过滤器 #}
            </li>
        {% endfor %}
        </ul>
    {% endarchiveParams %}
</div>

here,archiveParamsThe tag will get all custom parameters of the current article (archive.Id) and store them inspecsan array. Loop throughspecsto conveniently display each parameter'sName(parameter name) andValue(Parameter value). Please note thatparam.Valuerich text or HTML code may be included. It is imperative to use|safeA filter to ensure that HTML content is parsed and displayed correctly, rather than being escaped as plain text.

enhancementforadvanced techniques for the iterative experience

In addition to the basic traversal, AnQiCMS also provides some powerful auxiliary functions to make your template more expressive.forThe loop also provides some powerful auxiliary functions to make your template more expressive.

1. UseforloopVariables obtain loop information

InforWithin the loop, AnQiCMS will automatically provide a specialforloopvariable containing some useful loop information:

  • forloop.Counter: The current loop iteration number, starting from 1.
  • forloop.Revcounter: The reverse sequence number of the current loop, starting from the total count.

This is very useful when you need to add special styles to the first, last, or odd/even items in a list:

{% archiveList articles with type="list" limit="10" %}
    <div class="article-list">
    {% for article in articles %}
        <article class="article-item {% if forloop.Counter == 1 %}first-article{% endif %} {% if forloop.Counter is odd %}odd{% else %}even{% endif %}">
            <h3>{{ article.Title }} (第{{ forloop.Counter }}篇,还剩{{ forloop.Revcounter }}篇)</h3>
        </article>
    {% endfor %}
    </div>
{% endarchiveList %}

Byforloop.Counter == 1We can easily identify and style the first article, andforloop.Counter is oddIt can be used to implement the zebra line effect of list items.

2. UsereversedandsortedModifier

Sometimes we want to display the data in a specific order.forLoop supportreversed(Reverse) andsorted(Sort) modifier:

  • {% for item in collection reversed %}: Reverse traverse the data set.
  • {% for item in collection sorted %}: Traverse the data set after sorting it (default is ascending).

You can even combine them:{% for item in collection reversed sorted %}. This is very flexible when you need to display the same batch of data in different orders.

3. UsecycleLabel to implement style rotation

cycleTags are a very clever tool that can output the multiple values you define in order in a loop. This is very useful when you need to alternate between different background colors, CSS classes, or other variables:

`twig {% archiveList articles with type=“list” limit=“10” %}

<ul class="styled-list">
{% for article in articles %}
    <li class="list-item {% cycle

Related articles

What control flow tags does AnQi CMS template language support (such as if, for)?

## AnQi CMS template language: if, for, allowing flexible control of content display As an experienced website operation expert, I deeply understand the importance of a flexible and efficient content management system to a company.AnQiCMS (AnQiCMS) stands out in the content operation field with its high-performance architecture based on the Go language and its highly customizable nature.In daily content display and page construction, control flow tags in template languages, such as `if` and `for`, are undoubtedly the core tools for us to achieve dynamic and personalized content presentation. Today

2025-11-07

How to get the thumbnail or Logo of Tag in AnQiCMS template?

As an experienced website operation expert, I am well aware that how to flexibly use template tags to display a variety of content in a content management system is the key to enhancing the attractiveness and user experience of a website.AnQiCMS with its concise and efficient architecture and powerful template functions, provides us with great convenience.Today, let's delve into a common and practical need in content operation: how to obtain the thumbnail or Logo of a Tag in the AnQiCMS template.

2025-11-07

How to filter documents of specific models in the Tag document list of AnQiCMS template?

As an experienced website operations expert, I know that the flexibility of the Content Management System (CMS) is the key to improving operational efficiency and meeting various business needs.AnQiCMS (AnQiCMS) relies on its powerful content model and template system, providing great convenience for content operations.Today, let's delve into a very practical scenario in actual operation: how to accurately filter documents of a specific content model from the Tag document list in Anqi CMS template.Flexible control of content: The 'Model' and 'Label' in AnQi CMS

2025-11-07

What is the actual use of the index letter of Tag tags in AnQiCMS?

As an experienced website operations expert, I am well aware that every detail function of the content management system (CMS) can become the key to improving website operation efficiency and optimizing user experience.AnQiCMS (AnQiCMS) provides us with many such 'tools' with its concise and efficient architecture, and among them, the 'index letter' function of the Tag label, although seemingly minor, plays a crucial role in content operation strategy.Today, let's delve into the practical uses of this feature.

2025-11-07

How to determine if a variable is empty or execute conditional logic in AnQiCMS templates?

As an experienced website operation expert, I am well aware of how crucial precise control of template logic is when building and maintaining a high-efficiency, user-friendly website.Especially when using a content management system like AnQiCMS, which is based on Go language and focuses on performance and flexibility, it is possible to flexibly judge the status of variables and execute conditional logic according to different situations, which is the foundation for ensuring the correct display of content, avoiding page errors, and improving the user experience.The template engine of AnQi CMS uses a tagging style similar to Django

2025-11-07

How to reference the common header and footer files in AnQiCMS templates?

As an experienced website operations expert, I fully understand how important it is to maintain consistency in website structure and development efficiency in a content management system.Especially when using a highly efficient and flexible system like AnQiCMS, it is reasonable to refer to common header and footer files, which can not only greatly improve the maintenance efficiency of templates, but also ensure the unity of the entire site style.Today, let's delve into how to achieve this goal in AnQiCMS templates.AnQiCMS with its high-performance architecture based on Go language and Django-style template syntax

2025-11-07

How to implement nested category display in AnQiCMS template

As an experienced website operations expert, I am well aware of the value of a flexible and efficient content management system for the success of a website.AnQiCMS (AnQiCMS) relies on its high-performance architecture based on the Go language and the Django-style template engine, bringing great convenience and infinite possibilities to content display.Today, let's delve into a very common requirement in actual operation: how to implement nested display of multi-level categories in AnQiCMS templates, making your website structure clearer and enhancing the user experience.

2025-11-07

What are the common filters supported by AnQiCMS for processing template data (such as string truncation, date formatting)?

In the Anqi CMS template world, data is not just raw text or numbers, they are the foundation of excellent website content.However, the original data often needs to be polished before it can present itself in a certain posture to the user.At this time, the template filter has become an indispensable helper to us.They are like a Swiss Army knife for data processing, capable of performing various transformations, formatting, and refining template variables, bringing new luster to the data and meeting all kinds of display needs.As an experienced website operation expert

2025-11-07