How to loop through a list of data in a template and display it (using for loop), supporting counting and reversing?

Calendar 👁️ 59

In Anqi CMS template, efficiently displaying list data is an indispensable part of website content operation.Whether it is displaying the latest articles, product lists, category catalogs, or custom data sets, flexibly iterating through these data and performing fine-grained control can greatly enhance the performance and user experience of the website.The AnQi CMS provides a powerful and easy-to-use template engine, itsforThe loop tag is feature-rich, supporting not only basic traversal but also easily achieving counting, reversal, and more advanced operations.

Core Concept:forBasic usage of the loop

In the Anqi CMS template,forThe syntax of loops is very similar to the Django template engine, making it easy for users familiar with this type of syntax to get started quickly. Its basic structure is{% for item in collection %}...{% endfor %}. Here,collectionRepresents the collection of data you want to iterate over (for example, througharchiveList/categoryListdata obtained using tags), whileitemis the temporary variable representing the current data item in each iteration.

For example, if you want to display a list of recent articles that have been published, you would usually usearchiveListTag to get data, then throughforLoop through:

{% archiveList articles with type="list" limit="5" %}
    {% for article in articles %}
        <div class="article-item">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>{{ article.Description }}</p>
            <span>发布日期: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
        </div>
    {% endfor %}
{% endarchiveList %}

In this example,articleswe go througharchiveListthe collection of articles obtained,articleThis represents the variable for the current article object in each loop. You can rename it to any name that is easy to understand, as long as you keeparticlethe same meaning.forUse this variable within the statement.

Utility tools in loops: counting and status.

When traversing data in a loop, we often need to know which iteration we are currently in, or how many items are left. Anqi CMS'sforloops provide built-in variablesforloopIt includes the details of the current loop state, among which the most commonly used isforloop.Counterandforloop.Revcounter.

  • forloop.CounterThis variable starts from 1 and increments with each loop iteration, indicating the current item.This is very useful when you need to add numbering, ranking, or special treatment to the first item, last item, or any item in the list.
  • forloop.Revcounter: Similar toCounterOn the contrary,RevcounterStarting from the total number of items in the list, it indicates how many items (including the current item) are left to the end of the list. For example, if the list has 5 items,RevcounterIt is 5 in the first loop, 4 in the second, and so on, until the last item is 1.

CombineifLogic judgment tag, you can easily implement various conditional display effects. For example, add a special style to the first item in the list:

{% archiveList articles with type="list" limit="5" %}
    {% for article in articles %}
        <div class="article-item {% if forloop.Counter == 1 %}is-first{% endif %}">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>这是第 {{ forloop.Counter }} 篇文章,还剩下 {{ forloop.Revcounter - 1 }} 篇。</p>
        </div>
    {% endfor %}
{% endarchiveList %}

Byforloop.CounterYou can clearly know the progress of the current loop and adjust the presentation of the content accordingly.

Flexible control of order: flip and sort

Sometimes, we may need to display list data in different orders, such as displaying the latest content in reverse order or sorting by a certain attribute. Anqi CMS'sforLoops also provide a concise modifier for this:reversedandsorted.

  • reversed: This modifier will simply traverse the data collection in reverse order. If the data you retrieve from the database is sorted in descending order by time, but you want to display it in ascending order in the template, you can usereversed.
  • sorted: This modifier will perform a default sort on the dataset (usually in the natural order of the elements, such as numerical size or alphabetical order). Please note,sortedUsed to sort simple collections.
  • Combine usage:reversed sorted: You can combine these two modifiers. In this case, the list will be sorted first, and then reversed.

The following is usedreversedExample of displaying article list in reverse order:

{% archiveList articles with type="list" limit="5" %}
    {% for article in articles reversed %} {# 这里添加 reversed 翻转顺序 #}
        <div class="article-item">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>(倒序显示)发布日期: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</p>
        </div>
    {% endfor %}
{% endarchiveList %}

It should be noted that,sortedModifiers may not have the default sorting behavior you expect when handling complex collections of objects. For more complex sorting requirements, you may need to specify the sorting method when querying data on the backend, orforPerform data preprocessing outside the loop.

Handle empty list:emptyTag

When you try to iterate over a potentially empty list, you usually worry about blank areas or errors on the page. Anqi CMS'sforprovided a loopemptyThe label is used to display alternative content when the collection is empty, avoiding additionalifJudgment makes the template code more concise:

{% archiveList articles with type="list" categoryId="999" %} {# 假设分类ID 999下没有文章 #}
    {% for article in articles %}
        <div class="article-item">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
        </div>
    {% empty %} {# 当 articles 集合为空时,显示以下内容 #}
        <p class="no-content">当前分类下暂无文章,敬请期待!</p>
    {% endfor %}
{% endarchiveList %}

This way, even if there is no content under a certain category for the time being, your website can friendly prompt the visitor instead of displaying a blank.

Advanced技巧:neat output and nested loops

Remove logic label blank line

During template rendering,forLoop orifThe logic tags may cause unnecessary blank lines in the final HTML output, affecting the neatness of the HTML code. Anq CMS provides a trick to solve this problem: add a hyphen at the beginning or end of the tag-.

  • {%- for ... %}Remove whitespace before the tag.
  • {% endfor -%}Remove whitespace after the tag.

This minor change can make the generated HTML source code more compact.

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

Nested loop

For multi-level data structures, such as categories (first-level list) containing articles (second-level list), you can use nestedforloops to display. Anqi CMS'scategoryListandarchiveListLabels used together can achieve this effect:

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

{% for category in categories %}
    <div class="category-section">
        <h2><a href="{{ category.Link }}">{{ category.Title }}</a></h2>
        <ul>
            {% archiveList articles with type="list" categoryId=category.Id limit

Related articles

How to implement conditional (if/else) dynamic display of content and layout in a template?

In website operations and frontend development, we often need to flexibly display content or adjust the page layout according to different situations.This dynamic ability is the core value of the conditional judgment tag (`if/else`) in AnQiCMS templates.The Anqi CMS template engine is simple and powerful, allowing us to set logic on the page like writing program code, making the website content show endless possibilities.### The Dynamic Beauty of AnQi CMS Template

2025-11-08

How to customize the display template for specific articles, categories, or single pages to achieve personalized layout?

In website operation, providing exclusive display methods for specific content can significantly improve user experience and content marketing effectiveness.AnQiCMS (AnQiCMS) is well-versed in this field, providing flexible and diverse template customization features, allowing you to easily create a unique personalized layout for articles, categories, or single pages. The AnQi CMS realizes personalized template customization in two main ways: one is to follow specific **template file naming conventions**, the system will automatically identify and apply;Secondly, it is manually specified in the background management interface to use a custom template file.--- ### One

2025-11-08

How to modularize the header, footer, and other common parts in a template and reference them on each page to display uniformly?

In website operation, maintaining the consistency and efficient management of the website pages is the key to improving user experience and operational efficiency.For AnQiCMS (AnQiCMS) users, modularizing the header, footer, navigation bar, and other common parts not only ensures consistency in the overall visual style of the website but also greatly simplifies the maintenance and update work in the future.Strong and flexible template system provided by AnqiCMS, allowing you to easily achieve this goal.### Understanding AnQiCMS Template Architecture AnQiCMS template files are usually stored in

2025-11-08

What page adaptation modes are supported by AnQiCMS templates, and how to select and implement responsive display?

In the multi-screen era, users access websites through various devices, which has become the norm.To ensure that the website can provide a smooth and friendly experience on any device, page adaptation has become an indispensable part of website construction.AnQiCMS (AnQi Content Management System) fully considers this requirement, providing a variety of flexible template adaptation modes to help users easily cope with display challenges on different devices.

2025-11-08

How to avoid extra blank lines when template logical tags (such as if, for) are rendered on the page?

When developing templates in AnQiCMS, we often find that even though the template code itself looks neat, the final rendered HTML page may still contain some unexpected blank lines.These blank lines do not affect the page function, but may make the HTML source code look less tidy, and even in some extreme optimization scenarios, it may bring a slight increase in file size.For users who pursue code aesthetics and concise output, how to effectively avoid these redundant blank lines is a topic worth discussing.

2025-11-08

How to define and call the `macro` tag in AnQiCMS template to display reusable code blocks?

AnQiCMS provides a flexible and powerful template system, making the display of website content efficient and beautiful.In template development, in order to enhance the reusability and maintainability of code, we often encounter the need to encapsulate a commonly used code snippet so that it can be called in different places.This is when the `macro` tag becomes the key tool to achieve this goal.It allows us to define reusable code blocks, like functions in programming languages.Why do we need the `macro` tag?

2025-11-08

How to optimize page layout and content display by using the template inheritance (`extends`) tag?

In AnQiCMS, templates are the foundation for building the appearance and layout of a website.A well-designed template not only makes the website look professional and beautiful, but also greatly enhances the efficiency of content operation and the convenience of website maintenance.Among many powerful template tags, the `extends` (template inheritance) tag is undoubtedly one of the key tools for optimizing page layout and content display.It can help us build a unified and flexible website structure, making content operation and frontend development more effortless.### Understanding `extends`: The core of template inheritance `extends`

2025-11-08

How to declare a temporary variable in AnQiCMS template and use it to display content, improving template flexibility?

In the template creation of Anqi CMS, we often need to display various dynamic content.It is crucial to be proficient in using temporary variables to make templates more flexible and code more concise.The Anqi CMS template engine provides powerful functionality for declaring temporary variables, which helps us better organize and process data, thereby improving the efficiency and maintainability of content display.### Understanding the Value of Temporary Variables Imagine that you need to display processed data at multiple locations on the page, or that a piece of data is used repeatedly in conditional judgments, or that data obtained from a tag needs to be further processed before it can be presented

2025-11-08