How to use a for loop to traverse data and display it in the AnQiCMS template?

Calendar 👁️ 71

AnQiCMS with its flexible and powerful template system makes content display efficient and expressive.For website operators and developers, mastering how to iterate and display data in templates is a key step to unlocking their powerful features and bringing website content to life.forLoop, make your dynamic data easy to display.

AnQiCMS's template engine adopts syntax similar to Django, which allows users familiar with other mainstream template languages to quickly get started. In the template, when you need to display a series of data with the same structure, such as article lists, product categories, navigation menus, or image galleries, forThe loop is your powerful assistant.

The framework of the loop: basic syntax tutorial

forThe most basic form of a loop is to traverse a dataset (such as an array or list) and perform the same operation on each element. Its syntax is very intuitive:

{% for 变量名 in 集合 %}
    {# 在这里放置你希望对每个元素执行的代码 #}
    {{ 变量名.属性 }}
{% endfor %}

Here, 集合It is the dataset you want to iterate over, and变量名it represents the temporary name of the current element in each iteration. For example, if you have a list of articles namedarchivesyou can iterate over it like this:

{% archiveList archives with type="list" limit="5" %}
    {% for article in archives %}
        <div class="article-item">
            <h2><a href="{{ article.Link }}">{{ article.Title }}</a></h2>
            <p>{{ article.Description }}</p>
            <span>发布日期:{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
        </div>
    {% endfor %}
{% endarchiveList %}

This code will extract fromarchivesextract article data one by one from the collection, and display the current article's title, link, description, and publication date in each iteration.

Handle empty list:{% empty %}usefulness

Sometimes, the data set you iterate over may be empty. If displayed directly, the page may appear blank. AnQiCMSforprovided a loop{% empty %}The clause allows you to handle this situation gracefully:

{% archiveList recentPosts with type="list" limit="3" %}
    {% for post in recentPosts %}
        <div class="post-card">
            <h3><a href="{{ post.Link }}">{{ post.Title }}</a></h3>
        </div>
    {% empty %}
        <p>暂时没有最新文章发布。</p>
    {% endfor %}
{% endarchiveList %}

IfrecentPostsThere is data in the collection, it will normally display the article card; if not, it will display the prompt "There are no latest articles published yet." to avoid the page looking empty.

Enhance loop function: Sorting and reverse

AnQiCMS'forThe loop also supports some practical modifiers to allow you to more flexibly control the display order of data. You can addfora label directly afterreversedReverse iterate or usesortedSort the data (if the elements of the collection are of sortable numeric types):

{# 倒序显示文章列表 #}
{% archiveList latestNews with type="list" limit="5" %}
    {% for news in latestNews reversed %}
        <div class="news-item">{{ news.Title }}</div>
    {% endfor %}
{% endarchiveList %}

{# 假设有一个数字列表`numberList`,对其进行排序 #}
{% for num in numberList sorted %}
    <span>{{ num }}</span>
{% endfor %}

These modifiers can help you easily adjust the display of data on the front end without changing the original data acquisition logic.

Insight into loop progress:forloopPractical properties of objects

InforInside the loop, you can still access a specialforloopobject that provides various useful information about the current loop state. The most commonly used are:

  • forloop.Counter: The current iteration number of the loop, starting from 1.
  • forloop.Revcounter: The remaining iteration number of the loop.
  • forloop.First: If the current element is the first in the loop, thentrue.
  • forloop.Last: If it is the last element in the loop, thentrue.

Using these properties, you can add unique styles or behaviors to specific elements in the list:

{% archiveList products with type="list" limit="4" %}
    {% for product in products %}
        <div class="product-card {% if forloop.First %}first-item{% endif %} {% if forloop.Last %}last-item{% endif %}">
            <h3>{{ forloop.Counter }}. {{ product.Title }}</h3>
            <img src="{{ product.Thumb }}" alt="{{ product.Title }}">
        </div>
    {% endfor %}
{% endarchiveList %}

In this example, the first product card will be addedfirst-itemclass, the last one will be addedlast-itemclass, and each product will display its number in the list.

Creative display:{% cycle %}Tag

{% cycle %}The tag allows you to output different values in a loop. This is very useful for implementing zebra line effects (different background colors for odd and even rows), different animation classes in sliders, and other scenarios:

{% archiveList items with type="list" limit="6" %}
    {% for item in items %}
        <div class="item-row {% cycle 'bg-light' 'bg-dark' %}">
            <p>{{ item.Title }}</p>
        </div>
    {% endfor %}
{% endarchiveList %}

Each loop,item-rowalternates to obtainbg-lightandbg-darkclass, thus easily achieving a visual alternating effect.

Practical exercise: Application of for loop in common scenarios

After understanding the basic and advanced usage, let's take a look at some common loop application scenarios in AnQiCMS.for。“

1. Dynamic navigation menu

A typical website usually has multi-level navigation,forLoops handle this nested structure well.navListTags can retrieve navigation data, by判断item.NavListDoes it exist to implement the rendering of secondary even multi-level menus.

<nav>
    <ul>
        {% navList mainNav with typeId=1 %}
            {% for item in mainNav %}
                <li {% if item.IsCurrent %}class="active"{% endif %}>
                    <a href="{{ item.Link }}">{{ item.Title }}</a>
                    {% if item.NavList %} {# 如果有子导航 #}
                        <ul class="submenu">
                            {% for subItem in item.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 use an outer layerforLoop to handle the first-level navigation, and then use an inner layerforLoop to handle the secondary navigation.item.IsCurrentCan help you determine if the current link is selected, convenient for adding highlight styles.

2. Article/Product List Display

Whether it is the hot articles on the homepage or the product list on the category page,forLoops are at the core. CombinedarchiveListTags, you can easily display dynamic lists containing images, descriptions, and dates.

<div class="article-list">
    {% archiveList articles with type="list" moduleId="1" limit="10" order="views desc" %}
        {% for article in articles %}
            <article>
                {% if article.Thumb %}
                    <a href="{{ article.Link }}"><img src="{{ article.Thumb }}" alt="{{ article.Title }}"></a>
                {% endif %}
                <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
                <p>{{ article.Description|truncatechars:100 }}</p>
                <div class="meta">
                    <span>{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
                    <span>阅读量:{{ article.Views }}</span>
                </div>
            </article>
        {% empty %}
            <p>很抱歉,当前没有找到相关内容。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

Here we obtained the 10 most viewed articles, and we utilizearticle.ThumbCheck if there is a thumbnail,article.Description|truncatechars:100Truncate the description.

3. Display a group of images or an attachment list

On the article or product detail page, if the content model includes image galleries or attachment fields, they are usually stored in list form. You can directly iterate over these fields to display them.

`twig {# Assuming archive.Images is an array of image URLs #}

Related articles

How to implement conditional judgment in AnQiCMS template to control the display of content?

In AnQi CMS template design, flexibly controlling the display of content is the key to building dynamic, responsive websites.Whether it is to display different information based on page type, data status, or specific conditions, conditional judgment is an indispensable tool.The AnQiCMS template engine provides an intuitive and powerful conditional judgment mechanism, allowing you to easily implement these complex logic.### Core Grammar: The Basics of Conditionals The condition judgment in AnQiCMS templates is similar to many mainstream template engines, using the `{% if ... %}` tag structure

2025-11-08

How to format a timestamp and display it as a readable date and time in AnQiCMS?

In website content operation, time information plays an indispensable role.Whether it is the publication time of the article, the shelf date of the product, or the submission time of the comments, a clear and readable date and time format can greatly enhance the user experience.AnQi CMS as an efficient content management system, fully considers this point, and provides a flexible way to format and display these timestamp data.### Understanding Timestamps in AnQi CMS In the AnQi CMS backend, when we publish articles, products, or perform other content management operations

2025-11-08

How to get and display the list of friendship links configured in the AnQiCMS background?

In website operation, friendship links play an indispensable role. They not only bring valuable external traffic to the website but also help improve search engine optimization (SEO) effects, enhance the authority and credibility of the website.For users using AnQiCMS, managing and displaying friend links is a simple and efficient process.This article will introduce in detail how to configure friend links in the AnQiCMS background, as well as how to elegantly present them in your website front-end template.In AnQiCMS admin manage friend links First

2025-11-08

How to generate and display the website's message form in AnQiCMS templates?

In website operation, an efficient and convenient feedback form is an important bridge for user interaction with the website.It not only collects user feedback, but also serves as the entry point for potential customers to obtain information.AnQiCMS as an enterprise-level content management system provides powerful and flexible functions in this aspect, allowing us to easily generate and manage comment forms in templates.

2025-11-08

How to use AnQiCMS filters to truncate or convert text to uppercase and lowercase?

AnQiCMS provides powerful flexibility in content display, its template engine is built-in with a rich set of filters, helping users to easily process text without modifying the original content, including truncation and case conversion.These filters make the presentation of front-end content more accurate and beautiful, meeting the display needs of different scenarios.In AnQiCMS template syntax, the use of filters is very intuitive.You can apply a filter by adding a pipe symbol (`|`) after the variable name, if the filter requires parameters, then use a colon (`:`) after the filter name

2025-11-08

How to display the mobile URL of the website in AnQiCMS template?

When using AnQiCMS to build and manage websites, many friends may encounter such a need: If the website has an independent mobile version, how can you conveniently obtain and display the URL of this mobile website in the template?This makes it convenient for users to switch between different devices, and it also has a positive impact on search engine optimization (SEO).Don't worry, AnQiCMS provides a very intuitive way to achieve this.Why do we need to display the mobile URL in the template?First, let's talk about why there is such a need

2025-11-08

How to display the path of static files (CSS/JS/images) in AnQiCMS template?

When building a website with AnQiCMS, the correct reference to static files (such as CSS stylesheets, JavaScript scripts, and images) is the basis for ensuring the normal operation and beautiful presentation of the website.AnQiCMS provides us with a clear and flexible mechanism for managing and displaying these file paths, whether it is the static resources built into the template or the media files uploaded through the backend, there is a convenient way to reference them.

2025-11-08

How to implement multi-language content switching and display in AnQiCMS?

Today, having a website that supports multiple languages has become a key factor for enterprises to expand into international markets and enhance user experience.AnQiCMS is an efficient and flexible content management system that fully considers this need, providing you with a convenient multi-language content switching and display solution. Different from simply stacking multiple languages on the same page, AnQiCMS adopts a more flexible and powerful multi-site management mode to achieve multilingual support.

2025-11-08