How to use the 'loop iteration tag (for)' to display a dynamic data list in the template in AnQiCMS?

Calendar 👁️ 77

Website content needs to be constantly updated, such as displaying the latest articles, products, user comments, or navigation menus, and this dynamic data is often presented in the form of lists.In AnQi CMS, by using its powerful template engine and intuitive

The Anqi CMS template engine draws on the simplicity and efficiency of Django template syntax, making it easy for even developers who are new to it to quickly get started.Among them, the "loop traversal tag (for)" is the core tool we use to handle dynamic data lists, which helps us traverse various types of collection data and display its content one by one.

Get to know the 'Loop Iteration Tag (for)'

The basic syntax of the 'Loop Iteration Tag (for)' is very intuitive:

{% for item in collection %}
    {# 在这里显示每一个 item 的内容 #}
{% endfor %}

Here, collectionIt refers to a collection of multiple items, such as the article list, product list, or category list obtained from the background. anditemIt represents each independent data item in the collection, in each iteration of the loop,itemwill be assigned the next element in the collection. In this way, we can accessitemvarious properties of an object, for example{{ item.Title }}(article title) or{{ item.Link }}(article link), and present it on the page.

For example, if we want to display a list of the latest articles, it might be written like this:

{% archiveList archives with type="list" limit="5" %}
    {% for article in archives %}
        <div class="latest-article">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>{{ article.Description }}</p>
        </div>
    {% endfor %}
{% endarchiveList %}

This code first goes througharchiveListThe tag fetched the latest 5 articles and stored them inarchivesthe variable. Then,forLoop througharchivesEach article, name itarticleAnd display the title, link, and summary of each article within the loop.

Advanced usage: Make the list smarter

The “loop iteration tag (for)” is not just for simple iteration, it also provides various flexible options to make your list display more intelligent and diverse.

Handle empty data cleverly:{% empty %}温馨提示 of

Sometimes, the data list we obtain may be empty. In this case, if there is no prompt on the page, the user experience will be greatly reduced.forrepeatedly{% empty %}The clause is designed for this purpose:

{% for item in archives %}
    <div class="item-display">{{ item.Title }}</div>
{% empty %}
    <p>抱歉,目前没有找到相关内容。</p>
{% endfor %}

WhenarchivesThe loop continues as usual when the list is not empty; ifarchivesIf it is empty, then{% empty %}the content between them will be displayed, providing the user with a friendly feedback.

Customize the loop order:reversedandsortedMagic

You may wish to display the list data in a specific order.forLoop supportreversed(Reverse) andsorted(Sort) modifier:

  • reversed: Traverse the elements of the collection in reverse order. For example,{% for item in archives reversed %}.
  • sortedUsed to sort lists of numbers or strings in ascending order. For example,{% for item in numbers sorted %}.

This allows you to easily control the display logic of content, such as the latest content at the top, or sorted by views from high to low.

Data alternates display:cycleThe color game of tags

When designing tables or lists, we often need to implement alternating row styles (such as different background colors).cycleTags can help you output preset values in order each time during the loop:

{% for item in archives %}
    <div class="row-{% cycle 'odd' 'even' %}">
        {{ item.Title }}
    </div>
{% endfor %}

Each loop,cycleThey will output in turn'odd'and'even', adding visual hierarchy to your list.

Get loop information:forloop.Counterandforloop.Revcounter

Inside the loop, you can also access some special variables to get the state of the current loop:

  • forloop.Counter: indicates the number of iterations from1start counting.
  • forloop.RevcounterThis indicates how many iterations are left until the loop ends, starting from总数Start counting down.

This is very useful when you need to number list items or apply specific styles based on position:

{% for article in archives %}
    <div class="article-item {% if forloop.Counter == 1 %}featured{% endif %}">
        <span>{{ forloop.Counter }}.</span>
        <a href="{{ article.Link }}">{{ article.Title }}</a>
    </div>
{% endfor %}

Here, we not only added a serial number to each article, but also added an extra one to the first articlefeaturedthe class name.

Actual case: Dynamic data list display

The 'loop iteration tag (for)' in Anqi CMS, combined with various content tags, can flexibly construct various dynamic lists.

Article list: the most common application scenario

In addition to the simple article list displayed above, we can also combine more article fields to build a richer list:

{% archiveList articles with type="page" limit="10" categoryId="1" %}
    {% for item in articles %}
    <div class="post-card">
        {% if item.Thumb %}
        <a href="{{ item.Link }}" class="post-thumbnail">
            <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
        </a>
        {% endif %}
        <div class="post-content">
            <h2 class="post-title"><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
            <p class="post-excerpt">{{ item.Description|truncatechars:100 }}</p>
            <div class="post-meta">
                <span>发布于:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                <span>阅读量:{{ item.Views }}</span>
                <span>分类:<a href="{% categoryDetail with name='Link' id=item.CategoryId %}">{% categoryDetail with name='Title' id=item.CategoryId %}</a></span>
            </div>
        </div>
    </div>
    {% empty %}
    <p>此分类下暂无文章。</p>
    {% endfor %}
{% endarchiveList %}

This example shows a list of articles containing thumbnails, titles, abstracts, publication time, reading volume, and categories. Among themarchiveListThe tag specifies the category ID to be retrieved as 1 and enables pagination mode.

Categories and navigation: Build multi-level menus.

For the website's category menu, we usually need to display a multi-level structure. This can be easily achieved by nesting usingcategoryListTags andforloop, it can be easily implemented:

{% categoryList mainCategories with moduleId="1" parentId="0" %}
    <ul class="main-menu">
    {% for mainCat in mainCategories %}
        <li>
            <a href="{{ mainCat.Link }}">{{ mainCat.Title }}</a>
            {% if mainCat.HasChildren %}
            <ul class="sub-menu">
                {% categoryList subCategories with parentId=mainCat.Id %}
                {% for subCat in subCategories %}
                    <li><a href="{{ subCat.Link }}">{{ subCat.Title }}</a></li>
                {% endfor %}
                {% endcategoryList %}
            </ul>
            {% endif %}
        </li>
    {% endfor %}
    </ul>
{% endcategoryList %}

Here, the outer loop traverses the top-level categories, and the inner loop determines whether each top-level category has subcategories (mainCat.HasChildrenIf there are, retrieve and traverse the subcategories again to build a clear multi-level navigation structure.

Other dynamic data: friend links, banners, etc.

forThe versatility of the loop means it can be used for any data provided in a list form in the Secure CMS. For example, you can use it tolinkListTags andfordisplay links in a loop, or usebannerListTag display on homepage carousel:

`twig {# Friend link list #}

Related articles

How to safely output rich text content in AnQiCMS templates and avoid XSS attacks?

When building and operating a website, content display is undoubtedly the core link.Especially when displaying rich text content that includes images, links, bold, italic, and other formats, how to ensure that the page is beautiful while also effectively resisting potential security threats is a problem worth in-depth discussion.AnQiCMS (AnQiCMS) is a content management system that emphasizes security and efficiency, providing clear and strong mechanisms in this aspect.

2025-11-08

How to display custom contact information on AnQiCMS (such as WhatsApp, Facebook links)?

In today's digital age, a website is not just a platform for displaying information, but also an important bridge for businesses to connect with customers.Provide a variety of contact methods, such as WhatsApp, Facebook links, which can greatly enhance user experience and conversion efficiency.AnQiCMS as a powerful content management system provides a flexible and convenient solution in this regard.This article will introduce in detail how to set and display custom contact information in AnQiCMS, ensuring that your website can communicate with potential customers in the most convenient way.

2025-11-08

How to control the automatic compression of large images and the generation of thumbnails in AnQiCMS?

In website operation, images play a crucial role.They are not only elements that attract users' attention, but also directly affect the website's loading speed, user experience, and even the performance of search engine optimization (SEO).Managing website images, especially the compression of large-sized images and the generation of thumbnails, is a key link in improving website performance and aesthetics.AnQiCMS (AnQiCMS) fully understands this and provides flexible and powerful image processing features in its content management system, allowing you to easily control the automatic compression of large images and the generation of thumbnails.

2025-11-08

How does AnQiCMS automatically convert images to WebP format to speed up front-end loading?

In today's internet environment where content is exploding, the loading speed of a website is crucial for user experience and search engine rankings.Images are an important component of web content, and their loading performance is often a key factor affecting overall speed.AnQiCMS (AnQiCMS) understands this and provides the function of automatically converting images to WebP format, aimed at helping users effectively improve the front-end loading speed of websites.

2025-11-08

How to use the 'if logical judgment tag' in AnQiCMS template to control the conditional display of content?

## Flexible use of the "if" tag in AnQiCMS template to achieve accurate content presentation In website content management, we often need to display different content based on different conditions, such as displaying a prompt in a specific situation, displaying different information based on the user's identity, or only rendering a specific block when certain data exists. The AnQiCMS template system provides us with a powerful and easy-to-use "if logical judgment tag" that helps us easily achieve these dynamic content display needs

2025-11-08

How to customize the navigation menu in AnQiCMS and implement multi-level dropdown display on the front end?

In website operation, a clear and intuitive navigation menu is the core of user experience, as well as the key to content organization and promotion.AnQiCMS (AnQiCMS) fully understands this point, providing you with a flexible and powerful navigation menu customization feature, and supporting multi-level dropdown display on the front end to make your website structure clearer and content access more convenient.Next, we will together learn how to easily set up and apply these navigation in AnQiCMS.

2025-11-08

How to display the number of views and comments for articles in AnQiCMS?

In content operation, the number of page views and comments on articles is an important indicator of the popularity and user engagement of the content.They not only provide readers with references, but also help operators to understand content performance.AnQiCMS as a powerful content management system naturally also provides a convenient way to display these real-time data, making your website content more interactive and transparent.In AnQiCMS, whether it is articles, products, or other content types, they are all uniformly referred to as "documents" (archive)

2025-11-08

How to use Tag labels in AnQiCMS to associate and display related documents on the front end?

AnQiCMS provides powerful classification functions to organize the website structure, and also opens up new ways for deep association and multi-dimensional display of content through flexible Tag label mechanisms.Imagine that your website is like a library, with different shelves for categories, and Tag tags are like different subject keywords on books, allowing readers to find books with similar themes scattered on different shelves according to their interests.Next, let's delve into how AnQiCMS uses Tag labels to make your website content more intelligent and rich in front-end display

2025-11-08