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

Calendar 👁️ 64

In AnQiCMS, efficiently displaying content lists is a core requirement for website operation.Whether it is articles, products, categories, or custom data, we need a flexible mechanism to traverse and present this information.forLoop tags, it's like a helpful assistant that can help us easily achieve this goal.

Get to know the AnQiCMS template inforLoop tags

AnQiCMS's template syntax is based on the Django template engine, so it will be very quick for users familiar with similar syntaxes like Blade or Jinja2.forLoop tags are one of the core features, used to iterate over collections such as arrays or slices and process each item.

A basicforThis is how the loop structure looks:

{% for item in collection %}
    {# 在这里处理每个“item”的信息 #}
{% endfor %}

Here, itemIt is a temporary variable, which is assignedcollectionthe value of the current item in it.collectionThe collection you want to iterate through. The loop will end once all items have been traversed.

Handling the case of an empty list.

Sometimes, the dataset we get may be empty. To avoid the page from displaying blank or crashing,forLoop provides a very practical{% empty %}Label used to display a prompt when the collection is empty:

{% for item in collection %}
    {# 正常显示内容 #}
{% empty %}
    <p>抱歉,这里还没有内容。</p>
{% endfor %}

Progress of mastering the loop:forloopVariable

InforInside the loop, AnQiCMS also provides:forloopVariables, allowing you to better control the display logic of loops. The most commonly used include:

  • forloop.Counter: Represents the current iteration of the loop, starting from 1. This is very useful when you need to add numbers or specific styles to list items.
  • forloop.RevcounterIt indicates the remaining number of iterations in the current loop, counting from the total backwards.

For example, you can use them like this:

{% for item in archives %}
    <li class="{% if forloop.Counter == 1 %}active{% endif %}">
        <span>第 {{ forloop.Counter }} 篇,剩余 {{ forloop.Revcounter }} 篇</span>
        <h3>{{ item.Title }}</h3>
    </li>
{% empty %}
    <p>没有找到任何文章。</p>
{% endfor %}

Furthermore,forLoops also supportreversedandsortedModifiers, they can be used separately to reverse the order of the list or to sort according to the default sorting rules of the internal elements.

WithforLoop to provide data: content list label

forThe loop itself is just a processing logic, it needs to be "fed" data to work.In AnQiCMS, this data is usually provided by a series of dedicated content list tags, which query and organize the data from the database and return it as a collection (array/slice).

Common content list tags include:

  • archiveList: Used to retrieve a list of documents such as articles, products, etc.It is powerful and can filter data based on various conditions such as model ID, category ID, recommendation attributes, sorting method, and display quantity.
  • categoryListUsed to get category lists, such as article categories or product categories. It supports getting top-level categories, subcategories, or sibling categories.
  • pageListUsed to retrieve a single-page list, such as 'About Us', 'Contact Information', and other pages.
  • tagDataListUsed to retrieve the document list under a specified Tag.
  • linkListUsed to retrieve the list of friendship links.
  • bannerList: Used to get the list of home page banner images.

These tags, when used, usually assign the query results to a variable you specify, and then this variable can be used asforrepeatedlycollectionUsed.

Practice operation: How to display your content list

Now, let's look at how to use the AnQiCMS template through several specific examples.forLoop to traverse and display the content list.

Example one: Display the list of the latest published articles.

Suppose you want to display the latest 5 articles in the home page sidebar.

{# 使用 archiveList 标签获取文章列表,类型为 "list",限制数量为 5 篇 #}
{% archiveList latestArticles with type="list" limit="5" order="id desc" %}
    <div class="latest-articles">
        <h2>最新文章</h2>
        <ul>
            {# 遍历 latestArticles 集合 #}
            {% for article in latestArticles %}
                <li>
                    <a href="{{ article.Link }}" title="{{ article.Title }}">
                        {% if article.Thumb %}
                            <img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="article-thumb">
                        {% endif %}
                        <span class="article-title">{{ article.Title }}</span>
                        <span class="article-date">{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
                    </a>
                </li>
            {% empty %}
                <li>暂无最新文章。</li>
            {% endfor %}
        </ul>
    </div>
{% endarchiveList %}

In this example,latestArticlesWe usearchiveListThe collection of articles obtained by the tag, thenfor article in latestArticlesIt will iterate over this collection.article.Link/article.TitleAre the properties owned by each article item.stampToDateIt is a practical time formatting filter that can convert timestamps into readable date formats.

Example two: Display a navigation menu with subcategories.

Many websites have multi-level category navigation, we can utilizecategoryListand nestedforcycles to achieve.

{# 获取文章模型的顶级分类 #}
{% categoryList mainCategories with moduleId="1" parentId="0" %}
    <nav class="main-navigation">
        <ul>
            {% for category in mainCategories %}
                <li class="nav-item {% if category.HasChildren %}has-dropdown{% endif %}">
                    <a href="{{ category.Link }}">{{ category.Title }}</a>
                    {# 判断是否有子分类,如果有则再进行一次循环 #}
                    {% if category.HasChildren %}
                        <ul class="dropdown-menu">
                            {# 获取当前分类的子分类 #}
                            {% categoryList subCategories with parentId=category.Id %}
                                {% for subCategory in subCategories %}
                                    <li><a href="{{ subCategory.Link }}">{{ subCategory.Title }}</a></li>
                                {% endfor %}
                            {% endcategoryList %}
                        </ul>
                    {% endif %}
                </li>
            {% empty %}
                <li>暂无分类。</li>
            {% endfor %}
        </ul>
    </nav>
{% endcategoryList %}

We first obtain the top-level category, then in each loop of the top-level category, check if it has a subcategory (throughcategory.HasChildren). If it exists, use it againcategoryListGet its subcategory and display through the inner layerforDisplay in a loop.

Example three: Implement content pagination display

Pagination is indispensable for pages that require a large amount of content display, such as article list pages.archiveListcooperatepaginationTags can be easily implemented.

”`twig {# Get the pagination list of articles under the current category, with 10 articles per page #} {% archiveList paginatedArchives with type=“page” limit=“10” %}

<div class="article-list">
    {% for item in paginatedArchives %}
        <article class="article-card">
            <h2><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
            <p class="description">{{ item.Description }}</p>
            <div class="meta">
                <span>发布于:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>

Related articles

How to use the `include` tag in AnQiCMS templates to implement modular display of common components (such as headers and footers)?

When building a website, we often encounter such situations: the header (Header), footer (Footer), and some sidebars, navigation menus, and other components almost appear on every page.If each time these common sections of the code are written repeatedly, not only does it take time and effort, but also once it needs to be modified, it has to be searched and updated on each page, which is inefficient and prone to errors.

2025-11-07

How to define the basic layout in AnQiCMS templates and use the `extends` tag to unify the display style?

When building a website, maintaining a unified page style and clear structure is crucial for improving user experience and development efficiency.AnQiCMS provides a powerful and flexible template engine, which draws on the excellent ideas of Django templates, especially the use of the `extends` tag, making this goal achievable. ### The Foundation of a Unified Style: Basic Layout Template Imagine that your website is like a meticulously designed building, where each room has unique decorations, but the load-bearing walls, roof, and foundation are unified.

2025-11-07

How does AnQiCMS control the timing of content display on the website?

In content operation, the timing of content release is often a key factor in determining its effectiveness.In order to coordinate with marketing activities, meet traffic peaks, or simply to maintain the continuous update of website content, manual timing release not only takes time, but is also prone to errors.AnQiCMS knows this very well, therefore it provides a powerful and easy-to-use scheduled publishing feature, aimed at helping you easily solve the problem of content going live, ensuring that your content is always presented to your target audience at the right moment.When you create new articles, product introductions, or any other documents in the AnQiCMS backend

2025-11-07

How can AnQiCMS use SEO tools to improve the visibility of content in search engine results?

In the vast realm of digital marketing today, content creation is indeed important, but how to make these carefully crafted contents discovered by the target audience is the key to realizing their value.Search engine optimization (SEO) is the bridge connecting content to readers, and AnQiCMS, as an enterprise-level content management system, is well-versed in this, built-in with many powerful tools, aimed at helping users improve the visibility of their content in search engine results. We will delve deeper into how AnQiCMS can gain more exposure for your website content through its unique features.###

2025-11-07

How to filter and display the document list of a specified category or model with the `archiveList` tag in AnQiCMS?

AnQiCMS as an efficient enterprise-level content management system, provides users with flexible and diverse content management and display capabilities.When building a website, we often need to display document lists based on specific conditions, such as only showing articles in a particular category, or only listing entries of specific content models (such as products, services).At this time, the `archiveList` tag has become a powerful tool in our hands.It is not only powerful but also very intuitive to use, making it easy for us to meet these needs.### `archiveList`

2025-11-07

How to add pagination and optimize the display effect for document lists in AnQiCMS?

In website operation, how to efficiently display a large amount of content while ensuring the smoothness of user experience is a topic that cannot be ignored.The pagination feature of the document list is the key to solving this problem.AnQiCMS (AnQiCMS) is an efficient and flexible content management system that provides intuitive and powerful template tags, allowing you to easily add pagination features to document lists and optimize the display on top of that, making your website content more attractive.

2025-11-07

How to retrieve and display the complete content and properties of a single document using the `archiveDetail` tag?

When using AnQiCMS to build website content, displaying the complete information of a single document is one of the core requirements.No matter whether it is the detailed content of an article, a detailed introduction of a product, or any other specific entry of a custom content model, a highly efficient and flexible way is needed to extract and present this data.This is where the `archiveDetail` tag comes into play.

2025-11-07

How to display the link to the previous and next documents on the AnQiCMS document detail page?

In the ocean of website content, users often hope to browse related information smoothly, not wanting to return to the list to find the next article after reading a wonderful article.This not only affects user experience, but also benefits the internal link structure of the website and search engine optimization (SEO) a lot.AnQiCMS has fully considered this point, providing a convenient and quick navigation function for the content detail page, allowing users to easily navigate between different documents.The AnQiCMS template system is very flexible, it adopts the syntax of the Django template engine

2025-11-07