How to perform a loop (for) in Anqi CMS template to display list data?

Calendar 👁️ 57

When building a website page, we often need to display various list data, such as the latest articles, product categories, navigation menus, or comment details.The template system of AnQiCMS (AnQiCMS) provides us with a powerful and flexible loop traversal function, making the display of dynamic lists very simple.

The template syntax of AnQi CMS borrows from the Django template engine, so users familiar with this syntax will feel very comfortable. It usesforThe loop tag is used to traverse the data collection and display each item in the collection one by one.

Basic loop traversal in Anqi CMS template

The core loop traversal syntax is very intuitive:

{% for item in collection %}
    {# 在这里放置你的 HTML 代码和变量,用于显示每个 item 的数据 #}
    <p>{{ item.Title }}</p>
{% endfor %}

Here, collectionRepresents the data set you want to iterate through, for example, byarchiveListobtaining the list of articles through tags, or bycategoryListobtaining the list of categories. AnditemIt is the single data object being processed in the loop, you can access the various information of this data object throughitem.属性名to access the title of the data object, such asTitle), link (Link)ID(Id) and so on.

For example, if we want to display a simple list of article titles, we can do it like this:

{% archiveList archives with type="list" limit="5" %}
    <ul class="article-list">
        {% for article in archives %}
            <li>
                <a href="{{ article.Link }}">{{ article.Title }}</a>
            </li>
        {% endfor %}
    </ul>
{% endarchiveList %}

This code first usesarchiveListThe tag fetched the latest 5 articles from the background and assigned these data toarchivesVariable. Next,for article in archivesthe loop will process each one by one.archivesEach article in the loop, assigns the data of the current article toarticlethe variable, which we can then usearticle.Linkandarticle.Titleto construct the link and title of the article.

Explore Deep: Practical Techniques in Loops

In addition to the basic loops, Anqi CMS providesforLoops also provide some practical auxiliary functions to make list display more flexible.

1. Handle empty data:{% empty %}

If a data set is empty during iteration, you may want to display a prompt message instead of a blank page.emptyThe tags can be put into use:

{% for item in archives %}
    <p>{{ item.Title }}</p>
{% empty %}
    <p>抱歉,目前还没有任何内容。</p>
{% endfor %}

WhenarchivesWhen the list has no data,{% empty %}The content within the tags will be displayed.

2. Get loop information:forloopobject

InforInside the loop, you can access a specialforloopAn object that provides 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 number of iterations of the loop, counted from the total backwards.

This is very convenient when you need to handle specific items in the list (such as the first or last). For example, adding a prefix to the first item in the list.activeClass:

{% for item in archives %}
    <li {% if forloop.Counter == 1 %}class="active"{% endif %}>
        <a href="{{ item.Link }}">{{ item.Title }}</a>
    </li>
{% endfor %}

3. Sorting and Reversing:reversedandsorted

You can inforuse it directly in thereversedorsortedKeywords to change the order of traversal:

  • {% for item in archives reversed %}: Toarchivesreverse traverse the list.
  • {% for item in archives sorted %}: Try toarchivessort the list (this usually requires the elements in the list to be comparable, such as numbers or strings).

It should be noted that more complex sorting logic (such as sorting by publication time in reverse, sorting by view count, etc.), is usually implemented by obtaining the data list label (such asarchiveListUsed inorderparameters, for exampleorder="views desc".

4. Combine different list tags to obtain data

Anqi CMS provides a variety of list tags to obtain different types of data sets, which can be accessed throughforLoop through:

  • archiveListGet a list of articles, products, and other documents.
  • categoryListGet a list of categories.
  • navListGet the website navigation menu.
  • pageList: Retrieve a single-page list.
  • tagListGet a list of tags.
  • commentListGet a list of comments.
  • linkListGet the list of friend links.
  • bannerListGet the list of home page banners.

These tags all accept different parameters to precisely control which data to retrieve and assign the data set to a variable name, forforCyclic use.

Actual application scenarios and code examples

Let's demonstrate with several specific examplesforApplication of loops in Anqi CMS templates.

1. Display a list of articles with thumbnails and publication times

{% archiveList articles with type="page" limit="10" order="id desc" %}
    <div class="article-grid">
        {% for item in articles %}
            <article class="article-card">
                {% if item.Thumb %}
                    <a href="{{ item.Link }}" class="article-thumb">
                        <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
                    </a>
                {% endif %}
                <div class="article-info">
                    <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
                    <p class="article-desc">{{ item.Description|truncatechars:100 }}</p>
                    <div class="article-meta">
                        <span>发布日期:{{ stampToDate(item.CreatedTime, "2006年01月02日") }}</span>
                        <span>浏览量:{{ item.Views }}</span>
                    </div>
                </div>
            </article>
        {% empty %}
            <p>抱歉,目前没有找到任何文章。</p>
        {% endfor %}
    </div>
{% endarchiveList %}

In this example, we usearchiveListRetrieve the document and settype="page"(for pagination),limit="10"(10 items per page),order="id desc"(Sorted by ID in reverse order, i.e., the most recently published). Inside the loop, we displayed the article title, link, thumbnail, and summary, and thenstampToDateformatted the publish time.truncatechars:100The filter is used to truncate the introduction to avoid being too long.

2. Nested display of multi-level category navigation

Many websites need multi-level category navigation, which can be achieved through nestingcategoryListTags andforLoop to achieve:

`twig {% categoryList mainCategories with moduleId=“1” parentId=“0” %}

<nav class="main-nav">
    <ul>
        {% for mainCat in mainCategories %}

Related articles

How can conditional judgments (if/else) be used in the AnQi CMS template to control content display?

AnQiCMS template development skills: flexibly use conditional judgment (if/else) to control content display In website content operation, we often need to display or hide specific content blocks based on different conditions, or to differentiate the display based on different data states. AnQiCMS (AnQiCMS) powerful template engine provides us with flexible conditional judgment capabilities, through the clever use of `if/else` statements, you can easily achieve the fine-grained control of content, making your website more dynamic and user-friendly.

2025-11-08

How does the comment function of AnQi CMS display comment lists and reply levels?

AnQiCMS (AnQiCMS) as an efficient and flexible content management system, provides rich content display capabilities while also offering a comprehensive comment function for user interaction.Understand how to effectively display a comment list, especially in handling multi-level replies, which is crucial for enhancing the user engagement and content depth of a website. ### AnQiCMS Comment Function Implementation Basics Commenting functionality is an important part of website content interaction in AnQiCMS.The system is not only built-in with support for comments on articles, products, and other content

2025-11-08

How to add and display friendship links on the Anqi CMS website?

In website operation, friendship links play an indispensable role.They not only help to improve the search engine ranking (SEO) of a website, but also bring potential traffic and improve the user experience, allowing visitors to get more information through related websites.AnQiCMS (AnQiCMS) understands this and therefore provides an intuitive and convenient friend link management feature, allowing you to easily add, manage, and display these important external connections.This article will introduce in detail how to add friend links in the Anqi CMS background, as well as how to flexibly display them on the website's front-end template

2025-11-08

How to display and manage the website message form of AnQi CMS and customize fields?

The website message form is an important link between users and the website, it not only helps us collect valuable opinions and suggestions, but also lays the foundation for various interactive functions such as user consultation and service reservation.AnQi CMS is well-versed in this, providing website operators with a straightforward, efficient, and highly customizable feedback form solution, making it exceptionally simple to manage and customize form fields.### Easily build the frontend presentation of the message form In Anqi CMS, to display the message form on the website page, you do not need to write complex backend logic, just insert the specific tags in the template file

2025-11-08

How to format a timestamp into a readable date and time format and display it in AnQi CMS?

In website content operations, the presentation of time is often ignored, but it is an important detail for improving user experience and content professionalism.The original timestamp number lacks meaning for ordinary users. Formatting it into a clear and easy-to-read date and time format makes the content more appealing.AnQi CMS knows this, providing a simple and powerful way to handle such needs.### Understanding the timestamp in AnQi CMS In AnQi CMS, whether it is the publication time (`CreatedTime`) or the update time (`UpdatedTime`)

2025-11-08

Does AnQi CMS support the automatic conversion of uploaded images to WebP format for optimized display?

In the era where content is king, the loading speed of website images directly affects user experience and search engine optimization (SEO) performance.Efficient image management and optimization strategies are crucial for any website committed to providing high-quality content services.Many website operators are actively seeking solutions that can automatically optimize images, especially those converted to WebP format.So, for those who are using or considering using AnQiCMS, does this system support automatic conversion of images to WebP format after upload to optimize display?The answer is affirmative

2025-11-08

How to set up automatic image compression in Anqi CMS to speed up page loading?

Optimize images, speed up the website: AnqiCMS Automatic Compression Settings Guide Website access speed is one of the key factors in user experience and an important consideration for search engine optimization (SEO).And large images are often the culprit that slows down website loading speed.Fortunately, AnqiCMS, as a fully functional content management system, is built with a series of powerful image optimization features, which help us easily deal with this issue, while keeping the website smooth in providing rich visual content.Today, we will take a detailed look at how to use AnqiCMS

2025-11-08

How to configure content automatic external link filtering in Anqi CMS and how it affects the display of front-end links?

In website content operation, the management of external links is a vital aspect that cannot be ignored.It not only relates to user experience, but also directly affects the website's search engine optimization (SEO) performance.AnQi CMS knows this and therefore provides a flexible and practical external link handling mechanism to help content operators efficiently manage external links in articles.Where is the AnQi CMS external link configuration? AnQi CMS provides a very convenient function to handle external link issues, and you can easily configure it in the system background.The specific path is: log in to your AnQi CMS backend

2025-11-08