How does the `{% for ... in ... reversed %}` tag implement reverse traversal of a data list?

Calendar 👁️ 64

As an experienced website operations expert, I am well aware of the importance of content presentation for user experience and information communication.In AnQiCMS (AnQiCMS) such an efficient and flexible content management system, mastering its powerful template tag function is the key to our content精细化 operation.Today, let's delve deeply into a seemingly simple but extremely practical template tag modifier -{% for ... in ... reversed %}Look at how it plays a role in reverse traversal of the data list.


Advanced development of AnQi CMS template: Easily master the mystery of reverse traversal of data lists.

Today, with the rich digital content, how to efficiently and flexibly display website data is a subject that every website operator needs to face.AnQi CMS provides great convenience with its high-performance architecture based on the Go language and excellent support for Django template engine syntax.It allows us to present the backend data in various ways that are in line with business logic and user habits through concise and intuitive template tags.

Data list traversal is one of the most common operations in template development.Whether it is an article list, product display, user comments, or various dynamic data, we need to present them one by one through loop structures.The AnQi CMS template engine provides powerful{% for ... in ... %}Loop label, it can easily iterate over any iterable data collection, such asarchiveList(Document list),categoryList(Category list) data returned by tags. By default, these list data are usually sorted according to the database's default order (such as ID in ascending order) or the sorting rules we specify in the tags (such asorder="id desc"Descending ID is traversed.

However, in certain specific content operation scenarios, we may need to display the list data we have obtained in reverse order.For example, we may need to display the article with the earliest release, rather than the default latest release;Or in the comments section, although the data is stored in chronological order, we want to display it in reverse chronological order on the frontend, with the latest comments at the top.At this point, if the database query logic is modified again, it may increase unnecessary complexity, and may even not meet the needs of other modules for data order. At this time,reversedThe modifier comes into play, like a magic switch, instantly reversing the order of the data list display.

RevelationreversedModifier: The magic of reverse traversal.

{% for ... in ... reversed %}in the labelreversedis a powerful modifier, its function is very direct:It will changeinthe traversal order of the data set behind the keyword from the default forward to reverse.This means, if your data list was originally sorted in ascending order, you would addreversedAfter that, it will start traversing from the last element of the list until the first element; conversely, if the data list is already in descending order,reversedIt will start traversing from the first element (which is the smallest at this point).

The introduction of this modifier greatly enhances the flexibility of the front-end template, allowing us to meet the diverse content display needs simply by modifying the template code without touching the back-end data query logic.It operates on a dataset that has already been retrieved from the backend and passed to the template engine, therefore it does not impose any additional burden on the database query itself.

Actual application scenarios and code examples

Let's feel it through a few specific examples.reversedThe convenience and practicality of modifiers. Suppose we have a list of article data, through{% archiveList articles with type="list" limit="5" order="id asc" %}obtained 5 articles sorted by ID (i.e., from the earliest to the latest publication time).

1. Default or specified order traversal (sorted by ID in ascending order, i.e., the earliest articles first):

<div class="article-list">
    <h3>按发布顺序显示(最早的文章在前)</h3>
    {% archiveList articles with type="list" limit="5" order="id asc" %}
        {% for article in articles %}
            <p>{{ forloop.Counter }}. {{ article.Title }} - 发布时间: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</p>
        {% empty %}
            <p>暂无文章内容。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

This code will display articles by ID in ascending order, i.e., the earliest published articles first.

2. UsereversedPerform a reverse traversal (obtained in ascending order by ID, but displayed with ID in descending order, that is, the earliest article is at the end):

<div class="article-list-reversed">
    <h3>按反向发布顺序显示(最早的文章在后)</h3>
    {% archiveList articlesReversed with type="list" limit="5" order="id asc" %} {# 假设我们获取到的数据仍然是ID升序 #}
        {% for article in articlesReversed reversed %} {# 这里加入了 reversed 修饰符 #}
            <p>{{ forloop.Counter }}. {{ article.Title }} - 发布时间: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</p>
            {# 您可以使用 forloop.Revcounter 来获取倒序的计数,例如: #}
            {# <p>倒数第 {{ forloop.Revcounter }}. {{ article.Title }}</p> #}
        {% empty %}
            <p>暂无文章内容。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

Now, even though the data we get from the backend is in ascending order of ID, becausereversedThe modifier's role, the article list displayed on the page will be sorted in descending order of ID.That is to say, the first article in the list is now the last one obtained from the data, and so on.

Examples of application scenarios:

  • Historical Review Column:When you want to create a 'Website Development Timeline' or 'Historical Event Review' page, you may want to display the information in chronological order (from the distant past to the recent past). If your data is defaulting to the most recent at the front, then you need to add the data after obtaining itreversedJust do it.
  • Product clearance/old model display:On some promotional or product archive pages, you may need to prioritize the display of old model products,reversedwhich can help you quickly meet this need.
  • Comment list sorting adjustment:Although many comment systems default to the latest comments at the top, but sometimes in order to provide a different reading experience, or when the backend data is defaulting to chronological order, you can usereversedEasily switch the display order.

Byforloop.Counter(Count up) andforloop.Revcounter(Count down), you can better control the numbering or style of list items, which is useful when you usereversedIt is particularly useful when traversing in reverse, as it can help you verify whether the display order of the data meets expectations.

Cautionary notes and **practice

While usingreversedThere are several points to note when using modifiers:

  • Data source and sorting: reversedIt modifies the currentforThe collection being traversed. This means, it is when the data isarchiveListAfter the tags are obtained and prepared, they are then reversed. Therefore, if you have strict requirements for the original sorting of the data, it is best to do it inarchiveListetc

Related articles

How to elegantly display a 'no content' prompt when using the `empty` tag in AnQiCMS `for` loop?

In the daily operation of the website, we understand that the way content is presented is crucial to user experience.A well-designed website that not only provides rich information but also gives users friendly prompts when content is missing, avoiding the embarrassment of blank pages or error messages.

2025-11-06

How to get the remaining number of items in the current iteration of the `for` loop (reverse index)?

As an experienced website operations expert, I know that the template function of the content management system is the core of flexible and diverse content display on the website.AnQiCMS (AnQi CMS) leverages the efficient features of the Go language and the Django-like template syntax, providing us with powerful content operation support.Today, let's delve deeply into a practical skill often encountered in template development: how to elegantly obtain the remaining items of the current iteration in the `for` loop, which is what we often call the 'reverse index'.

2025-11-06

How to get the index starting from 1 in the current iteration of the `for` loop?

## How to skillfully use AnQiCMS template to easily get the "first" and "Nth" indices in the loop In website content operation, we often need to display a series of contents on the page, such as article lists, product displays, navigation menus, etc.In order to better present the content, we often need to fine-tune the control of each item in the list, such as adding special styles to the first item, or displaying the item's serial number in the list.

2025-11-06

How to use the `{% for ... in ... %}` tag in AnQiCMS templates to iterate over a data list?

How to flexibly use `{% for ...` in Anqi CMS templatein ...How to iterate over a data list with `%}` tag?As an experienced website operations expert, I fully understand the importance of an efficient and flexible template system for content management.AnQiCMS, as an enterprise-level content management system based on the Go language, draws on the essence of the Django template engine in template design, especially its powerful data traversal capabilities, particularly `{% for ...in ...The `tag is one of the core tools for building dynamic page content.

2025-11-06

How to correctly call the message form tag on the AnQiCMS website?

As an experienced website operation expert, I know the importance of the comment form in website operation.It is not only the bridge of communication between users and websites, but also the key point for us to collect user feedback, improve service quality, optimize content strategy, and even promote business growth.AnQiCMS as an efficient and customizable enterprise-level content management system provides strong and flexible support for the message function, allowing website administrators to easily build and manage various message scenarios.This article will focus on how to correctly call the comment form tag in the AnQiCMS website?This topic

2025-11-06

What specific fields information does the `fields` variable of AnQiCMS comment form tag contain?

As an experienced website operations expert, I fully understand the importance of a flexible and efficient website management system for content operations.AnQiCMS (AnQi CMS) is exactly relying on its powerful customization capabilities to allow content operators to freely create functions that meet business needs, among which the flexibility of the message form is one of its highlights.Today, let's delve deep into the `fields` variable in the AnQiCMS comment form tag, see what practical field information it contains, and help you build a more intelligent and user-friendly interactive module.### In-depth Analysis

2025-11-06

How to use AnQiCMS comment form tag to dynamically generate front-end form fields?

As an experienced website operation expert, I deeply understand the importance of a flexible and efficient content management system for a corporate website.AnQiCMS (AnQi CMS) stands out in the Go language CMS development field with its excellent customizability and ease of use.Today, let's delve into a powerful feature of AnQiCMS: how to cleverly use the comment form tag to dynamically generate front-end form fields.This can greatly enhance the flexibility of the website and make content operation more skillful.The value of the dynamic form

2025-11-06

What types of input fields are supported in the AnQiCMS contact form, and how to use them?

AnQiCMS Contact Form: The Secret to Flexible Customization and Precisely Reaching Users In today's digital age, a website is not just a platform for displaying information, but also an important window for deep interaction with users.Among them, the comment form serves as a bridge of communication between users and website administrators, and its usability and functionality directly affect the user experience and the efficiency of information collection.As an expert in website operations for many years, I deeply understand the importance of a flexible and customizable feedback form for enterprises to capture user needs and optimize service processes.

2025-11-06