The `for` loop tag can iterate over arrays, but it also supports advanced usages like `reversed` or `empty`?

Calendar 👁️ 58

The AnQi CMS template includesforLoop: More than just iteration, advanced techniques help you double your content operation efforts

As an experienced website operations expert, I fully understand the importance of an efficient and flexible content management system for a company.AnQiCMS (AnQiCMS) leverages its high-performance architecture based on the Go language and Django template engine syntax to provide strong support for our content creation and display.In daily operations, we often need to present data sets in list form on the website, at this time,forThe loop iteration tag is undoubtedly our powerful assistant.

However,forLoops are not just for simple iteration. Delve deeper into the potential of the Anqi CMS template tags, and you will find many advanced uses, such as handling data order.reversedandsortedand elegantly handling empty data,emptyeven with beautiful list display statements,cycleLabel and control of white space for optimized output. These techniques make the template code more concise and intelligent, thereby providing users with a smoother and more attractive reading experience.

Let's explore the Anqi CMS template togetherforThese advanced loop usages, see how to ingeniously integrate them into content operation strategies.

Solid foundation:forThe conventional application of looping through tags

Before delving into advanced usage, let's review firstforThe most basic and core function of looping is to traverse data sets. Whether it is an article list, product display or comment section,forLoops can present the data extracted from the backend one by one on the front-end page.

For example, if we want to display a list of the latest released documents, we would usually write the template code like this:

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

Here, archivesis a collection of documents,itemis the instance of the current document in each iteration. Moreover,forthe loop also provides built-inforloop.Counterandforloop.RevcounterVariables, they can display the current loop count (starting from 1) and the remaining loop count, which is very useful when you need to add numbering or special styles to list items:

{% for item in archives %}
    <li class="article-item">
        <span>第{{ forloop.Counter }}篇 / 剩余{{ forloop.Revcounter }}篇:</span>
        <a href="{{item.Link}}">{{item.Title}}</a>
    </li>
{% endfor %}

Beyond the norm:reversedwithsortedusefulness

Sometimes, the order in which data is displayed is not always default. For example, you may need to display the list content in reverse order, or you may want to sort it based on a field. At this point,reversedandsortedIt can be put to use.

When we want to iterate over the contents of a data set in reverse order, we just need to add in theforloop tag.reversedKeywords. This is especially convenient when displaying "latest comments" or "latest activities", if the data source is in default ascending order but the front-end needs to be in reverse order. For example, ifarchivesData is sorted by ID in ascending order by default, but if you want the latest articles (with the largest ID) to be displayed at the top, you can do it like this:

{% for item in archives reversed %}
    <div class="card-item latest-first">
        <h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
        <p>更新时间:{{stampToDate(item.UpdatedTime, "2006-01-02 15:04")}}</p>
    </div>
{% endfor %}

AndsortedKeywords allow us to sort data sets. The Anqi CMS template engine supports sorting of integer fields, with the default being ascending.This is very helpful in organizing content lists by view count, price, or other numeric custom fields.For example, if you have a parameter that contains numeric values such asViewsThe document list of views) and you want to display it from low to high by views, you can implement it like this:

{% archiveList archives with type="list" limit="10" order="views asc" %} {# 注意:这里order="views asc"已在archiveList标签中实现排序,sorted主要针对已获取的数组进行二次排序 #}
{% for item in archives sorted %} {# sorted这里会尝试对item.Id进行排序,如果需要按views排序,通常需要在archiveList标签中指定或通过后端处理 #}
    <div class="card-item popular-articles">
        <h4><a href="{{item.Link}}">{{item.Title}}</a></h4>
        <span>浏览量:{{item.Views}}</span>
    </div>
{% endfor %}

It is worth noting that,sortedIt is usually passed through data acquisition in the backgroundorderParameters specify sorting more efficiently, but in certain specific scenarios, if you need to sort an existing array twice on the front end (for example, sorting a simple field of a complex object array),sortedCan be used as a supplementary means. At the same time,reversedandsortedCan be used together, for example,{% for item in archives reversed sorted %}This will first sort the data, and then traverse the sorted results in reverse order.

Elegantly handle empty data:emptyStatement block

In content operation, we sometimes encounter the situation where the data set is empty.If this situation is not handled, a blank area may appear on the page, or even unfriendly error messages may be displayed, affecting the user experience.AnQi CMS offorprovided a loopemptyThis can solve the problem elegantly. Statement block

emptyStatement block inforThe loop is executed when there are no items to iterate over, which is equivalent to aif...elseA concise way. It allows you to提示用户 without data, rather than leaving a blank space:

{% archiveList searchResults with type="page" q=urlParams.q limit="10" %}
    {% for item in searchResults %}
        <div class="search-result-item">
            <h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
            <p>{{item.Description}}</p>
        </div>
    {% empty %}
        <div class="no-results-message">
            很抱歉,没有找到与“{{urlParams.q}}”相关的结果。
        </div>
    {% endfor %}
{% endarchiveList %}

Compared to判断 firstif searchResultsThen loop,emptyCode blocks make the logic clearer and more focused, and also more readable.

To add luster to the situation:cycleFlexible use of tags

To make the list display more visually appealing, we often use different styles to distinguish adjacent list items, such as the zebra striping effect. Anqi CMS'scycleThe label is born for this, it can output the predefined value sequence one by one in a loop.

cycleThe usage of labels is very simple, you can define multiple values in it, and a value will be taken out in order each time the loop runs, and it will start from the first value again after all the values have been taken out.

{% for item in archives %}
    <li class="article-row {% cycle "odd" "even" %}">
        <a href="{{item.Link}}">{{item.Title}}</a>
    </li>
{% endfor %}

In this example, list items will alternate usingoddandevenThese CSS classes can easily achieve a zebra pattern. You can also usecycleAssign the result to a variable so that it can be referenced multiple times in the template, making the code cleaner:

{% for item in archives %}
    {% cycle "bg-blue" "bg-white" as row_bg %}
    <li class="article-row {{ row_bg }}">
        <a href="{{item.Link}}">{{item.Title}}</a>
    </li>
{% endfor %}

Detail optimization: Techniques for controlling whitespace (-)

During template rendering,forloop,ifSentences and logical tags may produce unnecessary blank lines in HTML output, which does not affect the page function, but may make the final HTML code look less neat. AnQi CMS provides a small but powerful trick to solve this problem: add a hyphen at the beginning or end of the template tag-.

For example, a regularforA loop may produce additional blank lines:

{% for item in archives %}
    <div class="item">{{ item.Title }}</div>
{% endfor %}

IfarchivesThere is data, this code may have extra blank lines in eachdivBecause there are blank lines before and after the tags{% for %}and{% endfor %}The tag itself will occupy a line. To eliminate these blank lines, we can use-:

{% for item in archives -%}
    <div class="item">{{ item.Title }}</div>
{%- endfor %}

By adding in{% for %}added afterwards-%}and before{% endfor %}added before{%-Effectively remove these blank characters brought by template logic tags, generate a tighter HTML output, which is undoubtedly a blessing for operators who pursue ultimate page performance and code perfectionism.

Summary

Of Security CMSforLoop through

Related articles

Which conditional judgment operations does the `if` logical judgment tag support in the AnQiCMS template?

As an experienced website operation expert, I am well aware that a powerful and flexible template system is crucial for the effective presentation of website content.AnQiCMS (AnQi Content Management System) takes full advantage of its high efficiency based on the Go language and the grammar features borrowed from Django template engine, providing great convenience for our content operation.In AnQiCMS template development, proficiently using logical judgment tags is the key to achieving dynamic content display and enhancing user experience.Today, let's delve into the various conditional judgment operations supported by the `if` logical judgment tag in the AnQiCMS template

2025-11-06

How does the `stampToDate` tag format timestamps into any custom date and time format?

## Mastering AnqiCMS `stampToDate`: Easily Customize Time Display Format The way time information is presented is crucial in the daily work of content operation.Whether it is the release date of an article, the time a product is listed, or the moment a comment is submitted, a clear and readable date and time format can greatly enhance the user experience.However, we often get a series of difficult-to-understand Unix timestamps from the database - like the number `1609470335`. Don't worry

2025-11-06

How to use the `breadcrumb` tag in the AnQiCMS template to generate breadcrumb navigation?

As an experienced website operations expert, I know that a user-friendly and SEO-optimized website cannot do without a clear navigation structure, and breadcrumb navigation is the key link in this regard.It can not only help users understand their current location, improve the usability of the website, but also provide clear website structure signals for search engines.In AnQiCMS, integrating and using breadcrumb navigation is very simple and efficient, which is mainly due to its built-in `breadcrumb` tag. Today

2025-11-06

How to build a multi-level website navigation menu using the `navList` tag and support dynamic display of categories or document links?

As an experienced website operations expert, I am well aware of the importance of a clear and efficient website navigation system for improving user experience, guiding content consumption, and optimizing search engine rankings (SEO), which is self-evident.In AnQiCMS (AnQiCMS) such a well-designed content management system, building flexible and variable navigation menus, and making them able to intelligently display dynamic content, is the key to operators achieving fine-grained content layout.

2025-11-06

How to use `with` or `set` tags to define and assign variables in AnQiCMS templates?

AnQiCMS's template system is known for its flexibility and ease of use, providing strong support for content operators and developers.In the presentation of content, we often need to define temporary variables to handle data, optimize logic, or pass parameters.AnQiCMS template engine borrowed the syntax style of Django templates and provided two very practical tags to help us achieve this goal: `with` and `set`.Understanding their respective features and application scenarios can make your template code clearer and more efficient.

2025-11-06

How to implement code reuse and pass additional variables using the `include` tag in template development?

As an experienced website operations expert, I am well aware of the importance of template development efficiency and code maintainability for a website in my daily work.AnQiCMS (AnQiCMS) relies on its efficient architecture based on the Go language and the Django-style template engine, providing us with powerful content management capabilities.Today, let's delve deeply into a tool that can significantly improve efficiency and code reuse in Anqi CMS template development, namely the `include` tag, especially how it helps us achieve code reuse and flexibly pass additional variables.

2025-11-06

How to implement template inheritance with the `extends` tag and overwrite specific blocks of the parent template?

As an experienced website operations expert, I deeply understand that a flexible and efficient template system is crucial for the long-term development of a website.In AnQiCMS (AnQiCMS), it draws on the powerful capabilities of the Django template engine, allowing you to manage the website interface in a simple and logical way.Today, we will focus on one of the core features - the `extends` tag, and delve into how it implements template inheritance, allowing us to accurately rewrite specific blocks of the parent template.

2025-11-06

How to define and call the `macro` macro function in the AnQiCMS template to create reusable code snippets?

In the process of website operation and development, we always encounter the need to repeatedly write similar code segments, such as unified article card styles, product information display modules, or form elements with specific interactions.If you start from scratch every time, it is not only inefficient, but also makes maintenance a nightmare.AnQi CMS is well-versed in this, its powerful template engine provides us with the 'macro' macro function, a tool aimed at helping developers and operators easily create reusable code snippets

2025-11-06