How to use a loop (for label) to traverse and display a content list?

Calendar 👁️ 61

In AnQi CMS, whether it is to display article lists, product catalogs, navigation menus, or friend links, we will frequently deal with content lists.To dynamically display this content on the website front-end, a powerful loop function is indispensable.Today, let's delve deeper into how to use the loop in the Anqi CMS template (forTag) to traverse and display your content list.

forThe core syntax of the tag: make the content dynamic

The template syntax of AnQi CMS is similar to Django and Blade, very intuitive. When you need to handle a group of data,forTags are your helpful assistants. Their basic structure is very simple:

{% for item in collection %}
    {# 在这里显示每个item的详细信息 #}
{% endfor %}

Here, collectionIt refers to the collection of content you want to traverse, such as byarchiveListorcategoryListTags get the list of articles or categories.itemIt represents the current element of the collection in each iteration, you can accessitemto display specific content.

For example, suppose you want to display the latest several article titles and links:

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

In this example,latestArticleswe go througharchiveListThe article list obtained by the tag.forthe loop,articleThe variable represents an article in each iteration. We can accessarticle.Linkthe article link byarticle.Titleaccess the article title and display it on the web page.

Loop through the content list: take the document list as an example

The document list is one of the most common dynamic content on websites. ThrougharchiveListLabel, we can easily obtain document data under articles, products and other models, thenfordisplay them in a loop.

For example, you want to display a list of documents under a category, including the title, summary, and publication time:

{% archiveList documents with categoryId="1" type="list" limit="10" %}
    <div class="documents-section">
    {% for doc in documents %}
        <div class="document-item">
            <h3><a href="{{ doc.Link }}">{{ doc.Title }}</a></h3>
            <p>{{ doc.Description }}</p>
            <p class="meta">发布时间:{{ stampToDate(doc.CreatedTime, "2006-01-02") }}</p>
            {% if doc.Thumb %}
                <img src="{{ doc.Thumb }}" alt="{{ doc.Title }}" class="document-thumbnail">
            {% endif %}
        </div>
    {% endfor %}
    </div>
{% empty %}
    <p>当前分类下没有可用的文档。</p>
{% endarchiveList %}

Here, we usearchiveListGot 10 documents under category ID 1.for doc in documentsloop:

  • doc.Linkanddoc.TitleIt provided the link and title of the document.
  • doc.DescriptionIt is used to display the introduction of the document.
  • doc.CreatedTimeIt is a timestamp, we cooperatestampToDatetags to format it as a readable date.
  • doc.ThumbThe thumbnail of the document is displayed andifThe tag determines whether an image exists.

Useful tips in the loop

To make your content display more flexible and beautiful, AnQi CMS'sforTags also provide some practical auxiliary functions.

  1. Handle empty list:emptyTagWhen your content collection may be empty,emptytags can be used. Ifforthe loop has no iterable elements.itemthenemptyThe content within the tags will be displayed, to avoid blank pages or errors.

    {% for item in someList %}
        {# 列表内容 #}
    {% empty %}
        <p>暂时没有相关内容可供显示。</p>
    {% endfor %}
    
  2. Get loop number:forloop.Counterandforloop.RevcounterInside the loop,forloop.CounterCan get the current loop number (starting from 1),forloop.RevcounterThen get the remaining number of items in the current loop. This is very useful when different styles need to be applied to specific items (such as the first or last item).

    {% for item in documents %}
        <div class="document-item {% if forloop.Counter == 1 %}first-item{% endif %}">
            <span class="item-number">{{ forloop.Counter }}.</span>
            <h3>{{ item.Title }}</h3>
        </div>
    {% endfor %}
    
  3. Adjust the traversal order:reversedandsortedSometimes you may need to display the content in a different order.reversedKeywords can allow you to traverse the collection in reverse, whilesortedKeywords can sort the collection (for sortable types).

    {# 倒序显示文章 #}
    {% for article in latestArticles reversed %}
        ...
    {% endfor %}
    
    {# 排序显示文章(通常结合后台排序参数更常用) #}
    {% for article in latestArticles sorted %}
        ...
    {% endfor %}
    

    However, in Anqi CMS, we usually specify sorting methods througharchiveListsuch as tags,orderparameters, which is more direct and efficient.

  4. to display different contents at intervals:cycleTagIf you want to alternate the display of different values in a loop, for example, setting different background colors for odd and even rows of a list,cycleTags are a good choice.

    {% for item in documents %}
        <div class="document-item {% cycle "odd" "even" %}">
            {# ... 内容 ... #}
        </div>
    {% endfor %}
    

    Then, the first item will getoddthe class, the second item getseventhe class, the third item goes back tooddand so on.

  5. Clean code: Remove extra blank linesTo maintain the conciseness of generated HTML, you can utilize{%-and-}Remove extra whitespace before and after tags. This is particularly useful in scenarios where a large number of elements are generated in a loop.

    {% for item in documents -%}
        <div class="document-item">
            {# ... 内容 ... #}
        </div>
    {%- endfor %}
    

Nested loop: Handling multi-level data

When dealing with multi-level classification or complex data structures, nested loops are indispensable.For example, you can traverse the top-level categories first, and then traverse the subcategories or documents belonging to each top-level category inside.

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

This example shows how to

Related articles

How to dynamically display different content blocks based on conditions (if tag)?

In Anqi CMS, the dynamic display of website content is the key to improving user experience and operational efficiency.You often encounter such needs: you want a certain content block to appear only under specific conditions, or to display different information for different situations.At this point, the powerful conditional judgment feature of Anqi CMS - the `if` tag, can be put to good use.The Anqi CMS template system adopts a syntax similar to the Django template engine, allowing you to implement logical judgments in templates in a straightforward manner.By flexibly using the `if` tag, you can easily control the display and hide of web elements

2025-11-08

How to display the background custom banner (Banner) image list in the template?

The banner image on the website is an important element to attract visitors' attention and display core information.In Anqi CMS, you can flexibly customize these banner images in the background and elegantly present them in various template positions on the website.Below, we will discuss in detail how to display the custom banner image list in the template, making your website more attractive. ### Configuration and Management of Background Banner Images In the Anqi CMS backend, the management of banner images is mainly divided into two cases: global homepage banners and specific content banners. 1.

2025-11-08

How to convert image addresses to thumbnail format for display?

In website operation, images play a crucial role.They can not only attract users' attention but also effectively convey information.However, very large images can severely affect website loading speed, thereby damaging user experience and search engine rankings.Therefore, converting the image address to a thumbnail format for display has become an indispensable part of optimizing website performance.AnQiCMS provides very convenient features in this aspect, it can automatically generate and manage thumbnail images for your website, and also provides flexible calling methods to help you easily meet the challenges of image optimization.### AnQiCMS

2025-11-08

How to truncate long text content and add an ellipsis at the end to optimize list display?

In website operation, especially managing a content-rich platform, the display effect of the list page is crucial for user experience.Whether it is an article list, product overview, or news update, we hope the page is tidy and the information is clear at a glance.However, when the document content or description is too long, directly displaying it in the list often leads to layout confusion, affecting the overall aesthetics and information acquisition efficiency.At this moment, effectively truncating text and adding an ellipsis is particularly important.AnQiCMS (AnQiCMS) provides a powerful and flexible template system, in which built-in text filters can help us easily solve this problem

2025-11-08

How to format a timestamp into a readable date and time string for display?

In Anqi CMS, formatting timestamps into readable dates: A practical guide When managing website content, we often encounter the need to display article publishing time, update time, and user registration time information.These data are usually stored in the database in the form of a string of numbers - that is, a 'timestamp'.Although computers can easily understand these numbers, they may not seem so friendly to users visiting websites.For example, seeing a number like '1678886400' is not as intuitive as '2023 March 15 10:00:00'

2025-11-08

How to define template variables and reuse them in content display?

In AnQi CMS, managing and displaying website content, flexibly using template variables is undoubtedly the key to improving efficiency and maintaining consistency.Whether it is necessary to unify the information of the entire site or to customize unique attributes for specific content, understanding how to define and reuse template variables can make content operation more skillful. ### From the background source to define variables In AnQi CMS, many of the information we see on the website every day is actually managed through backend predefined variables.This means you don't have to touch a single line of code to easily define and modify these contents. First

2025-11-08

How does Anqi CMS manage and display uploaded images and video resources?

When using Anqi CMS to manage website content, images and video resources are undoubtedly the key to enriching the page and improving the user experience.AnQi CMS provides a set of intuitive and powerful functions to help us efficiently upload, manage, and display these multimedia contents. ### Easy upload and centralized management of resources When creating articles, products, or single-page content, images and videos can be directly inserted into the content editing area.This process is very smooth, just like using a document editor in everyday life.In addition to this immediate insertion method, Anqi CMS also has a dedicated "image resource management" area

2025-11-08

How do static rules affect the display form and SEO-friendliness of website URLs?

## Static rule of AnQi CMS: How to create a URL structure that users and search engines both love In the operation of a website, the URL is not only the path for users to access the page, but also an important clue for search engines to understand and evaluate the content of the website.A clear, concise, and meaningful URL that greatly enhances user experience and website SEO performance.AnQi CMS knows this, and therefore provides a flexible and diverse static rule management function to help us easily create an ideal URL structure.What is pseudo-static and why is it so important

2025-11-08