How to use a `for` loop to iterate over data and handle `empty` data situations?

Calendar 👁️ 59

As an experienced CMS website operation person in AnQi, I fully understand the importance of content in attracting and retaining users.Dynamic, responsive website content display is the key to improving user experience, and effectively handling data sets, especially when the data may be empty, is a basic skill in operational work.AnQiCMS (AnQiCMS) powerful template engine provides us with flexible tools to achieve these goals, among whichforLoop tags and theiremptyA block is our powerful assistant for content display.

Dynamic content display withforThe core role of the loop

The template engine of AnQi CMS adopts a syntax similar to Django templates, which allows us to control the rendering of page content in a straightforward manner.When building a website, we often need to display a series of contents, such as article lists, product displays, image galleries, or navigation menus, etc.This content is usually sourced from a database and passed to the template in the form of a collection (such as an array or a slice). At this point,forThe loop has become the foundation for traversing and displaying each item in turn.

forThe basic syntax of the loop is concise and clear, it allows us to specify a variable to represent each element in the collection and define how to display this element inside the loop:

{% for item in collection %}
    {# 在这里定义如何展示 item #}
    <div class="content-card">
        <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
        <p>{{ item.Description }}</p>
    </div>
{% endfor %}

For example, when we usearchiveListThe label retrieves a series of article data from AnQi CMS,archivesThe variable will contain an array of article objects. By using the aforementionedforloop, we can easily traversearchiveseach article in theitem),and display its title, link, and description properties, thereby building a dynamic article list page.

Elegantly handle empty data:emptythe practice of blocks

In website operation, the data set may be empty. For example, there may be no articles under a certain category, or no matching items in the search results.If this situation is not handled, the front-end page may display a blank, causing confusion to the user.In order to avoid this situation, the Anqi CMSforthe loop tag provides a very practicalemptythe block.

{% empty %}the block allows us toforWhen iterating over an empty collection, a backup content is displayed. This greatly enhances the user experience, allowing users to receive clear feedback even when there is no content to display.

Combineemptyblock'sforThe loop syntax is as follows:

{% for item in collection %}
    {# 当 collection 不为空时,遍历并展示 item #}
    <div class="content-card">
        <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
        <p>{{ item.Description }}</p>
    </div>
{% empty %}
    {# 当 collection 为空时,显示此内容 #}
    <div class="empty-state-message">
        <p>当前没有任何内容可供显示。</p>
        <p>您可以尝试浏览其他分类或使用不同的搜索关键词。</p>
    </div>
{% endfor %}

Suppose we use{% archiveList archives with type="page" limit="10" %}Tag to get a paginated list of articles. Ifarchivesthe variable is empty, the template will not enter{% for ... %}the normal display logic inside, but render the content directly{% empty %}in the block. This is better than manually adding{% if archives %}and{% else %}Judgment should be more concise and elegant, and also more in line with the semantic design of the template.

forAdvanced techniques of loops

In addition to basic traversal and empty data processing, Anqi CMS'sforThe loop also provides some powerful auxiliary functions that can make our content display more flexible:

  • forloop.Counterandforloop.Revcounter: Within the loop, we can useforloop.CounterGet the current loop index (starting from 1), andforloop.RevcounterIt indicates the number of items remaining from the current item to the end of the loop. This is very useful for adding numbers to list items, implementing alternate row coloring, or applying specific styles based on position.

    {% for item in archives %}
        <li class="{% if forloop.Counter is odd %}odd-row{% else %}even-row{% endif %}">
            <span>{{ forloop.Counter }}.</span>
            <a href="{{ item.Link }}">{{ item.Title }}</a>
        </li>
    {% endfor %}
    
  • reversedandsortedKeyword: We can directly be infor specify the traversal order of data in the loop.reversedIt will traverse the collection in reverse, whilesortedAttempts to sort the collection (usually in the default natural order). These two keywords can also be combined, for example{% for item in archives reversed sorted %}.

    {% for item in archives reversed %}
        <p>最新发布:{{ item.Title }}</p>
    {% endfor %}
    
  • cycleTag: When we need to repeat a series of values in a loop (for example, to alternate CSS classes for list items),cycleThe tag comes into play. It will output predefined values in order according to the number of cycles.

    {% for item in products %}
        <div class="product-item {% cycle 'bg-light' 'bg-dark' %}">
            <h3>{{ item.Title }}</h3>
        </div>
    {% endfor %}
    

Application scenarios and **practice

In the operation practice of AnQi CMS,forLoop withemptyThe block's application is ubiquitous. Whether it's displaying popular articles on the homepage, all products under the category page, or the data list of custom models in the backend, we should follow the following practices:

  1. Always consider the state of empty data: When designing templates, anticipate the case where the data set is empty, and utilize{% empty %}Blocks provide friendly prompts or guidance, rather than leaving users to face a blank page. This helps improve user satisfaction and reduce the bounce rate.
  2. Use auxiliary variables reasonably:forloop.CounterVariables can help us implement complex layout and style logic, reducing the workload of front-end JavaScript.
  3. Keep the code concise: Use{% empty %}Avoid long-windedness.{% if ... else ... %}structure. Moreover, for extra blank lines generated by template logic tags, you can use the-symbol to remove, for example{%- for item in collection -%}, in order to ensure that the final HTML structure is more compact.

Through proficiencyforloop and itsemptyA block, we can build a complete and user-friendly security CMS website, effectively supporting various content operation activities.


Frequently Asked Questions (FAQ)

1. How toforHow to get the current loop number in the loop?

You can useforloop.CounterA variable is used to obtain the current loop index, which starts from 1. If you need to start from 0, although the AnQiCMS template does not provide it directly,forloop.Counter0but you can use{{ forloop.Counter - 1 }}to achieve.

2.{% empty %}Can the block handle all types of null values, such asnilorfalse?

{% empty %}The block is mainly used to check if an iterable collection (such as a list, array) is empty. Ifcollectionthe variable itself isnilor an empty collection,emptyA block will be triggered. It usually does not directly handle boolean valuesfalseor other 'empty' values of non-collection types. For these cases, you shouldforUse outside the loop{% if ... %}make a logical judgment.

3. I can beforuse labels insideifDo you want to filter or conditionally display data?

Absolutely, you can.{% for ... %}Loops are responsible for traversing all elements in a collection, while{% if ... %}you can use statements to manipulate each one inside the loopitemPerform a conditional judgment to determine whether to display this item or display it in a different way. The combination of these two tags is a common practice for building complex dynamic content layouts.

Related articles

How does the Anqi CMS template support `if`, `elif`, `else` logical judgments?

In Anqi CMS template design, conditional logic judgment is an indispensable part for realizing dynamic content display and complex layout control.As a website operator, I am well aware that flexibly using `if`, `elif`, `else` and other logical judgment tags can allow us to present a wide variety of page content based on different data states or business requirements, thereby enhancing user experience and the interactivity of the website.The Anqi CMS template engine supports syntax similar to the Django template engine, which allows users familiar with other mainstream CMS template languages to quickly get started

2025-11-06

How to implement and display pagination navigation on list pages (such as article lists, search results)?

As an experienced CMS website operations personnel for an Internet security company, I know that the details of content presentation are crucial for user experience and website SEO.Page navigation is one of the fundamental and key components, which not only helps users efficiently browse a large amount of content, but also allows search engines to better crawl and index website information.Today, I will elaborate on how to elegantly display pagination navigation on the list page of AnQi CMS, such as article lists, search result pages, etc.### Overview of Pagination Mechanism in AnQi CMS Implementing pagination functionality in AnQi CMS is intuitive and efficient

2025-11-06

How to retrieve and display the list of友情链接 configured in the background?

As an experienced CMS website operation personnel, I fully understand the importance of efficient content management and front-end display for the success of the website.Friend links are an important part of a website's external cooperation and SEO optimization, and their convenient acquisition and display methods are an indispensable part of daily operation.Now, I will elaborate on how to obtain and display the list of友情链接 links configured in the AnQiCMS admin panel.### AnQi CMS: Efficient management and display of the background friendship link list Friendship links, as an important part of website external link construction

2025-11-06

How to embed and display a user留言表单in a template?

As a website operator who deeply understands the operation of AnQiCMS, I fully understand the importance of providing user interaction channels on the website.The user feedback form is a key tool for collecting feedback, answering questions, and building relationships with users.In AnQiCMS, embedding and displaying a comment form through its flexible template engine is a direct and highly customizable process.This article will detail how to implement this feature in the AnQiCMS template.

2025-11-06

How to format a timestamp from a database into a readable date and time string?

As an experienced CMS website operation personnel of AnQi, I know that the content of the website should not only be rich, but also presented in a user-friendly manner.Time information is an important part of the content, but the timestamps (Unix timestamps) stored in the database are often just a string of numbers, which can be confusing to display directly.Therefore, formatting these timestamps into easily readable date and time strings is a key step in enhancing user experience and increasing content readability.

2025-11-06

How to define a temporary variable and perform assignment operations in a template?

Hello! As an experienced AnQi CMS website operator, I am very happy to be able to explain in detail how to define and assign temporary variables in AnQi CMS templates.This is crucial for achieving the flexibility, readability, and maintainability of templates, enabling us to organize and display website content more efficiently.In the Anqi CMS template system, we often encounter scenarios where we need to store data, calculate results, or prepare content for specific components locally.To meet these requirements, Anqi CMS provides a concise and powerful variable definition mechanism, mainly realized through two tags

2025-11-06

What are the different roles of the three auxiliary tags `include`, `extends`, and `macro` in template structure organization?

As an experienced CMS website operation personnel of AnQi, I am well aware of the importance of a clear and efficient template structure for content management and website maintenance.In AnQi CMS, the template engine provides various auxiliary tags to help us better organize and reuse template code, among which `include`, `extends`, and `macro` are the three great tools for building a flexible template architecture.They each have different responsibilities, but together they serve to enhance the maintainability and development efficiency of the template.### Modular content reuse

2025-11-06

How to use built-in filters (such as `truncatechars`, `upper`) to process and convert the data format of template variables?

As an experienced AnQiCMS website operation person, I am fully aware of the importance of content in attracting and retaining users.High-quality content not only requires careful creation, but also needs to be presented in an appropriate format and optimized to enhance user experience and readability.AnQi CMS, with its flexible Django template engine syntax, provides us with powerful built-in filter functions, allowing us to easily process and convert the data format of template variables.Next, I will give a detailed introduction on how to use the built-in filter of Anqi CMS

2025-11-06