How to use the `for` loop tag to iterate and display list data in AnQiCMS template?

Calendar 👁️ 65

In AnQiCMS templates, dynamically displaying list data is one of the core operations for building rich website content. Whether it is displaying the latest articles, hot products, category lists, or any custom content collection,forLoop tags are your helpful assistants. They allow you to easily traverse data and customize the display of each item according to your needs.

UnderstandingforThe basic of loop tag

forThe loop tag is a control structure used in the AnQiCMS template engine to iterate over a collection of data. Its basic syntax is very intuitive:

{% for 变量名 in 集合 %}
    <!-- 在这里编写您希望重复显示的内容 -->
{% endfor %}

Here, 集合It is the list of data you want to iterate over,变量名It represents a temporary name for the current data item in each loop. For example, if you have a list of articlesarchivesyou can use it like thisforLoop:

{% for article in archives %}
    <h3>{{ article.Title }}</h3>
    <p>{{ article.Description }}</p>
{% endfor %}

In each loop,articlethe variable will point toarchiveseach article data in the list, you can use{{ article.字段名 }}The syntax to access the various properties of the current article, such as the title (Title) and descriptions (Description)

Get list data:forThe foundation of loops

In AnQiCMS,forThe data that loops can iterate over usually comes from various list tags, such asarchiveList(Document list),categoryList(Category list),pageList(single-page list) andtagDataList(Tag associated document list) etc. These tags are responsible for retrieving and organizing data from the background and then passing the results toforrendering in a loop.

Start witharchiveListFor the document list as an example, it provides a wealth of parameters to help you accurately filter and sort data. Some commonly used parameters include:

  • moduleIdSpecify which content model (such as article model or product model) document to retrieve.
  • categoryId: Specify the category of documents to retrieve. If you want to retrieve documents from all subcategories, you can keep the default value; if you only want to retrieve documents from the current category, you can specify it explicitlychild=false.
  • limit: Controls the number of returned documents, for examplelimit="10"Only 10 will be displayed.
  • order: Defines the sorting rules, for exampleorder="id desc"(Sorted by ID in descending order, i.e., the most recent published),order="views desc"(sorted by view count in reverse, i.e., the most popular).
  • typeSpecify the list type,type="list"Used for non-paginated fixed quantity lists,type="page"Used for paged lists (usually combined withpaginationUse the tags).

While usingforBefore the loop, you need to use these tags to get the data set. For example, to get the list of the latest 10 articles, you can write like this:

{% archiveList archives with moduleId="1" order="id desc" limit="10" %}
    <!-- 这里的archives变量就是for循环的数据源 -->
    {% for item in archives %}
        <!-- 循环显示文章内容 -->
    {% endfor %}
{% endarchiveList %}

In this example,archivesIt is througharchiveListThe article data collection obtained by the tag is thenforThe loop is used to traverse.

Traverse and display list data: practical exercise

Now we combinearchiveListandforLoop to display how to show a list of articles. Suppose we need to display the latest 5 articles on the homepage, including their titles, links, publication time, thumbnails, and summaries.

<div class="latest-articles">
    <h2>最新文章</h2>
    <ul>
        {% archiveList articles with moduleId="1" order="id desc" limit="5" %}
            {% for item in articles %}
                <li>
                    <a href="{{ item.Link }}">
                        {% if item.Thumb %}
                            <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
                        {% endif %}
                        <h3>{{ item.Title }}</h3>
                    </a>
                    <p class="summary">{{ item.Description }}</p>
                    <p class="meta">
                        发布于:{{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}
                        浏览量:{{ item.Views }}
                    </p>
                </li>
            {% empty %}
                <p>暂无最新文章。</p>
            {% endfor %}
        {% endarchiveList %}
    </ul>
</div>

In this example:

  • We usearchiveListWe obtained the article list and named itarticles.
  • {% for item in articles %}Start the loop,itemRepresents the current article.
  • {{ item.Link }}/{{ item.Title }}/{{ item.Thumb }}Retrieve the article link, title, and thumbnail separately.
  • {% if item.Thumb %}Used to determine if a thumbnail exists, to avoid empty image tags.
  • {{ item.Description }}Display the article summary.
  • {{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}Then it used the AnQiCMS providedstampToDatefunction to format the article's publish timestamp.
  • {{ item.Views }}Displays the number of views of the article.
  • {% empty %}block inarticlesFriendly prompts are provided when the list is empty.

Improve user experience:foradvanced usage of loops

forThe loop is not only capable of simple traversal of data, it also has some special variables and modifiers built-in to help you achieve finer control.

Loop status variable

InforInside the loop, there are some special variables that can help you understand the state of the current loop:

  • forloop.Counter: Indicates the current loop index, starting from 1.
  • forloop.Revcounter: indicates the index from the end of the loop, starting from 1.

This is very useful when you need to add special styles to the first, last, or specific elements in a list.

{% for item in articles %}
    <li {% if forloop.Counter == 1 %}class="first-item"{% endif %}>
        <!-- 内容 -->
        <p>这是第 {{ forloop.Counter }} 篇文章,距离末尾还有 {{ forloop.Revcounter }} 篇。</p>
    </li>
{% endfor %}

Loop modifier

You can also modifyforthe way loops are traversed:

  • reversedTraverse the collection in reverse order.
  • sorted: Traverse the collection after sorting it (applies to sortable collections, such as numeric or string lists).
<!-- 按发布时间从旧到新显示 -->
{% archiveList articles with moduleId="1" order="id asc" limit="5" %}
    {% for item in articles %}
        <!-- 内容 -->
    {% endfor %}
{% endarchiveList %}

<!-- 如果数据集合本身是无序的,但您想在模板中进行反向遍历 -->
{% for item in some_other_list reversed %}
    <!-- 内容 -->
{% endfor %}

Handle empty data:{% empty %}block

When the data collection you obtain may be empty, use{% empty %}The block can elegantly handle this situation instead of displaying a blank page or error.

`html {% archiveList search_results with moduleId=“1” q=“keyword” type=“list” limit=“10” %}

{% for item in search_results %}
    <p>搜索结果:{{ item.Title }}</p>
{% empty %}
    <p>抱歉,没有找到符合您条件的文章。</p

Related articles

How to use `if-else` conditional tags to control the display logic of content in AnQiCMS templates?

In AnQiCMS templates, make good use of the `if-else` conditional judgment tag to make content display more intelligent In website content operation, we often need to display different content or styles according to different conditions.For example, when the article list is empty, display 'No content', when an article is in the recommended state, add a 'HOT' mark, or add a special style to the first item in the loop.

2025-11-07

How to use Django template engine syntax to efficiently display various dynamic content in AnQiCMS?

In AnQi CMS, you will find that the built-in Django template engine syntax is an extremely powerful and flexible tool, which can help you efficiently convert backend data into dynamic and lively content on the frontend page.Master this syntax, and you'll not only be able to display basic text and images, but also build complex, interactive dynamic pages, making your website vibrant.The template syntax design of Anqi CMS is very intuitive, it draws on the characteristics of the Django template engine and integrates the concise and efficient Go language.

2025-11-07

Where should the AnQiCMS template files be stored, and what file extensions are supported?

AnQiCMS is designed very clearly and flexibly in template file management, aiming to allow users to customize the appearance and functions of the website efficiently.If you are using AnQiCMS to build or maintain a website, understanding the location of template files and supported suffixes is the foundation for front-end development and customization.

2025-11-07

How to customize templates in AnQiCMS to change the overall visual style and layout of the website?

In this era that emphasizes brand and user experience, the visual style and layout of a website is the key to its successful operation.AnQiCMS (AnQiCMS) understands this point and therefore provides a highly flexible template customization feature, allowing users without a strong development background to create websites that meet their unique needs with a personalized touch.If you are considering changing the overall style of the website or want to design a dedicated layout for specific content, it will be very helpful to understand how to customize templates in AnQiCMS.

2025-11-07

How does AnQiCMS support the switching of multiple templates, as well as how to specify an independent template for a specific page or content type?

## The flexible aspects of AnQiCMS: How to handle multi-template switching and personalized page design A flexible template mechanism is crucial for a content management system to maintain competitiveness and adapt to diverse operational needs.AnQiCMS is an efficient enterprise-level content management system that has demonstrated excellent capabilities in this regard. It not only supports multi-template switching at the whole-site level but also provides detailed features for specifying independent templates for specific pages or content types. This is undoubtedly a powerful tool for websites that need to carry out refined content operations. Firstly

2025-11-07

How to retrieve and display the title, detailed content, summary, and recommended attributes of an article (document)?

In Anqi CMS, whether it is to display the detailed content of a single article or to preview multiple articles on the list page, flexibly obtaining and displaying the title, detailed content, introduction, and recommended attributes of the article is the foundation of website operation.The design of Anqi CMS makes this process intuitive and efficient, we mainly achieve it through template tags and variable calls.First, understand the template system of Anqi CMS is crucial.

2025-11-07

How to effectively retrieve and display a thumbnail, cover main image, or a collection of multiple images for an article?

In content operation, captivating images are an indispensable element to attract readers and enhance the quality of articles.AnQiCMS (AnQiCMS) understands this and provides a diverse and flexible set of features, whether it's for the thumbnails of article lists, the cover images on detailed pages, or rich multi-image collections, all can be easily obtained and displayed in the way you expect.How does AnQi CMS handle various images?In AnQi CMS, images are usually divided into several types to meet the display needs of different scenarios: * **Article Thumbnail (Thumb):**

2025-11-07

How to implement the pagination display function of AnQiCMS article list, as well as how to customize the pagination style and logic?

In content operation, the pagination display of the article list is a basic and crucial function, which not only affects the user's browsing experience, but also is closely related to the performance and SEO performance of the website.AnQiCMS as an efficient and customizable content management system provides us with a flexible way to implement and beautify the pagination function of the article list.

2025-11-07