How to use a for loop to traverse an array and handle an empty array in Anqi CMS template

Calendar 👁️ 67

During the template development process of AnQi CMS, dynamic data display is one of the core requirements.Whether it is an article list, product display, or navigation menu, we cannot do without traversing array or collection data.And in this process, how to elegantly handle the case of empty data, ensuring the beauty of the page and user experience is equally important.

The AnQi CMS template engine supports powerful features similar to Django template syntax, includingforThe loop is a powerful tool for processing data lists. It also provides a very practical{% empty %}The label is specifically used to handle the scenario where the data collection is empty, making our template code more concise and robust.

UnderstandingforBasic usage of loops

In the Anqi CMS template,forThe syntax of loops is very intuitive, allowing us to access each element of a data collection one by one. Typically, you will see such a structure:

{% for item in collection %}
    {# 在这里使用 item 来访问集合中的每个元素属性 #}
{% endfor %}

here,collectionrepresent the data array or list you want to iterate over, anditemIt is the temporary variable for each iteration of the current element in the loop. For example, when you need to display the latest list of articles, you can call it like thisarchiveListTag to get data, then useforLoop through:

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

In this example,latestArticlesIt is an array that contains multiple articles,articlewhich represents the current article in each loop, you can directly access its properties througharticle.Title/article.Linkand so on.

Furthermore,forLoops also provide some useful built-in variables, such asforloop.CounterYou can get the current number of times the loop runs (starting from 1),forloop.RevcounterIt can obtain the number of remaining elements, which is very convenient when adding special styles to elements at specific positions.

Gracefully handle empty arrays:{% empty %}Tag

In practical applications, a dataset may become an empty array due to various reasons (such as no content published, empty filtering results, etc.). If you only use the above mentionedforA loop, when the collection is empty, no content will be displayed on the page, which may cause the page layout to appear blank, even confusing the user.

To solve this problem, the Anqi CMS template engine introduced{% empty %}a tag. This tag is specifically used withforlooping, whenforthe loop tries to traverse thecollectionis empty,forThe content inside the loop will be skipped and executed instead{% empty %}The content inside the tag. This allows you to display a friendly prompt or alternative content when there is no data.

Its basic syntax is as follows:

{% for item in collection %}
    {# 正常遍历时显示的内容 #}
{% empty %}
    {# 当 collection 为空时显示的内容 #}
{% endfor %}

Compared with the traditional way of first usingifThe statement to determine the length of the collection, and then decide whether to proceedforLoop,{% empty %}The style is undoubtedly more concise and semantically meaningful. For example, if the above list of articles may be empty, we can improve it like this:

{% archiveList latestArticles with type="list" limit="5" %}
    {% for article in latestArticles %}
        <div class="article-summary">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>{{ article.Description|truncatechars:100 }}</p>
            <small>发布日期: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</small>
        </div>
    {% empty %}
        <div class="no-content-message">
            <p>抱歉,目前没有最新的文章可供展示。</p>
            <p>您可以查看其他分类或稍后再回来!</p>
        </div>
    {% endfor %}
{% endarchiveList %}

By adding{% empty %}a block whenlatestArticlesWhen there are no articles, users will not see an empty area, but will see the prompt

More practical scenarios

{% empty %}Tags are not only suitable for article lists, but also can be very useful in any scenario that requires traversing arrays in Anqi CMS templates.

For example, when building website navigation, if there are no sub-navigations under a certain category, you can{% empty %}to control the display style:

{% navList mainNavigation %}
    <ul class="header-nav">
        {% for navItem in mainNavigation %}
            <li>
                <a href="{{ navItem.Link }}">{{ navItem.Title }}</a>
                {% if navItem.NavList %} {# 检查是否有二级导航 #}
                    <ul class="sub-nav">
                        {% for subNavItem in navItem.NavList %}
                            <li><a href="{{ subNavItem.Link }}">{{ subNavItem.Title }}</a></li>
                        {% empty %}
                            {# 如果某个一级导航下没有二级导航,这里可以留空或显示其他内容 #}
                        {% endfor %}
                    </ul>
                {% endif %}
            </li>
        {% empty %}
            <p>网站导航配置中...</p>
        {% endfor %}
    </ul>
{% endnavList %}

For example, when you need to display the custom parameters of a document, these parameters are also returned in array form. If the document has not set any custom parameters,{% empty %}they can be used:

{% archiveParams docParams with sorted=true %}
    <div class="document-parameters">
        <h4>文档属性</h4>
        {% for param in docParams %}
            <p><strong>{{ param.Name }}:</strong> {{ param.Value }}</p>
        {% empty %}
            <p>此文档未设置任何额外的自定义属性。</p>
        {% endfor %}
    </div>
{% endarchiveParams %}

In practical development, use flexiblyforloop and{% empty %}The label can help us build a more flexible, user-friendly Anqi CMS website template.Always consider the scenario where data is empty and prepare in advance, which is an indispensable practice in template development.


Frequently Asked Questions (FAQ)

1.forCan loops be nested?

Yes,forLoops fully support nesting. For example, when building multi-level classification navigation, you can in aforUse another inside the loopforLoop to traverse subcategories, as shown in the navigation menu example in the article. However, it is recommended not to nest too deeply to avoid affecting the readability and performance of the template.

2. Besides{% empty %}Label, are there other methods to determine if an array is empty and display alternative content?

Of course there are. Although{% empty %}It is the simplest and recommended way to handle empty arrays in Anqi CMS templates, but you can also use traditionalifstatements to combine|lengthfilters to determine the length of an array. For example:

{% if collection|length > 0 %}
    {% for item in collection %}
        {# 遍历内容 #}
    {% endfor %}
{% else %}
    <p>没有数据可显示。</p>
{% endif %}

This method is also effective, but relatively speaking,{% empty %}more semantically meaningful, and the code is also more concise.

3. InforHow do I get the current index of a loop (for example, to determine if it's the first or last element)?

InforInside the loop, you can use a specialforloopvariable to get this information:

  • forloop.Counter: The current loop count (starting from 1).
  • forloop.Counter0: The current loop count (starting from 0).
  • forloop.Revcounter: The remaining loop count (counting down from the total).
  • forloop.Revcounter0: The remaining number of iterations (counting down from the total, starting from 0).
  • forloop.First: Boolean value, if it is the first iteration, then true.
  • forloop.LastBoolean value, if it is the last loop iteration, thentrue.

For example, you can judge like this: “`twig {% for item in collection

Related articles

How to use if/else condition judgment to control content display in Anqi CMS template?

In AnQi CMS template creation, flexibly controlling the display of content is the key to improving website user experience and management efficiency.Whether it is to display specific information based on different conditions, or to implement more complex personalized layouts, conditional judgment is an indispensable tool.Today, we will delve into how to use the powerful `if/else` conditional judgment in Anqi CMS templates to accurately control the presentation of content. The template engine of AnQi CMS adopts syntax similar to Django template syntax, which allows web developers familiar with web development to quickly get started. Among them

2025-11-08

How to perform initial arithmetic operations on user input data in AnQi CMS template?

In AnQiCMS template design, performing preliminary arithmetic operations on user input data is a key link in achieving dynamic content display and interactive logic.AnQiCMS powerful template engine, draws on the characteristics of Go language and Django templates, providing developers with flexible and easy-to-understand arithmetic calculation capabilities, allowing you to handle various numerical logic in front-end templates without writing complex backend code.

2025-11-08

How to get the friend link in Anqi CMS template and set the nofollow attribute?

In website operation, friendship links are an important means to enhance website authority and obtain external traffic.However, not all friendship links should pass on weight. It is particularly important to use the `rel="nofollow"` attribute reasonably to better manage the SEO performance of the website.The `nofollow` attribute tells search engines not to pass ranking weight from the current page to the target page, which is very useful when linking to non-core content, advertising pages, or third-party websites that cannot be fully trusted, and can effectively avoid SEO risks caused by low-quality links

2025-11-08

How to get the website name in Anqi CMS template and correctly concatenate it in the SEO title?

In website operation, a well-constructed SEO title is crucial for attracting user clicks and improving search engine rankings.It must not only accurately summarize the page content but also ingeniously integrate the brand information.For AnQiCMS users, how to dynamically obtain the website name in the template and correctly concatenate it into the SEO title is a practical and efficient skill.AnQiCMS as a content management system that focuses on SEO optimization, provides very flexible tags at the template level, allowing you to easily achieve this goal.

2025-11-08

How can I customize the content display layout of the AnQi CMS website?

The layout of website content display is a key factor in attracting visitors, enhancing user experience, and optimizing search engine rankings.A clear, beautiful, and functional layout that can make your website stand out among competitors.AnQiCMS (AnQiCMS) is an efficient content management system that provides high flexibility, allowing you to customize the display of website content according to your actual needs.This article will deeply explore how to customize the content display layout of the Anqi CMS website, helping you turn your creativity into reality and create a website with a unique style.--- ###

2025-11-08

What are the conventions for naming and storing AnQi CMS template files?

When you start using Anqi CMS to build a website, understanding the naming rules and storage path conventions of its template files is the key to efficient website design and content presentation.A clear file structure can not only help you quickly locate and modify templates, but also make team collaboration smoother, ensuring stable operation of the website. ### The "home" of template files: unified storage location All template files of AnQi CMS are stored centrally in the `/template` folder under the project root directory.This is like a large library, where all books (template topics) are collected here

2025-11-08

How to effectively organize and reference website static resources (CSS/JS/images)?

Building and managing websites in AnQiCMS (AnQiCMS), efficient organization and referencing of static resources (CSS styles, JavaScript scripts, images, etc.) is the key to improving website performance, ease of maintenance, and user experience.Our Anqi CMS provided us with clear guidelines and practical features, helping us easily cope with these challenges. ### One: A Clear and Ordered Directory Structure: The Way to Organize Static Resources Good file organization is the foundation of efficient management of static resources.In AnQi CMS

2025-11-08

How are the syntax rules of template variables and tags similar to Django?

When building and customizing the AnQiCMS website, the template plays a core role.AnQiCMS's template system draws on the power and simplicity of the Django template engine, which means that whether you are new to it or already familiar with other modern template languages, you can quickly get started.The syntax rules revolve around how to effectively display dynamic data and control page logic, making the website content flexible and organized.Understand the core of the AnQiCMS template system, you first need to distinguish between two main elements: variables and tags.

2025-11-08