How to elegantly handle empty list situations in AnQiCMS template using the `{% for ... empty ... %}` syntax?

Calendar 👁️ 62

In AnQiCMS template development, we often need to display a series of content lists, such as article lists, product lists, navigation menus, or friend links.However, these lists are not always filled with data. When a list is empty, how to elegantly inform the user that "there is no content here" instead of displaying a blank or error message, has become a detail to consider in template design.AnQi CMS is well-versed in this, drawing on the excellent design of Django templates in its powerful template engine developed in Go language, providing us with{% for ... empty ... %}This concise and practical syntax.

AnQiCMS as an enterprise-level content management system, its template engine design aims to provide high flexibility and ease of use.It adopts a syntax style similar to the Django template engine, making it easy for front-end developers to get started quickly.{{变量}}Refer to it, and logical control, such as conditional judgment and loop, is implemented through single curly brackets and the percent sign.{% ... %}Define. This clear syntax structure provides strong support for content presentation, while also ensuring the readability and maintainability of the code.

{% for ... empty ... %}The core of elegant handling of empty lists.

When processing a dynamic content list,forLoops are undoubtedly the most core tag. They allow us to iterate over an array or slice and other iterable objects, processing each element. A typicalforThe loop might look like this:

{% for item in archives %}
    <li>
        <a href="{{item.Link}}">{{item.Title}}</a>
        <p>{{item.Description}}</p>
    </li>
{% endfor %}

This code can render each item in the article list well. But the problem is that ifarchivesThis list happens to be empty, and the page will be empty, which greatly reduces the user experience. To avoid this situation, we usually add an extra one.ifCheck if the list is empty.

However, the Anqicms template engine provides a more elegant solution, which is to introduce in the{% for ... %}loop.{% empty %}Block. ThisemptyThe block's function is very intuitive: whenforThe list iterated by the loop is empty (i.e., there are no elements to iterate over) at the time, the content within the loop will not be executed, instead, it is replaced by{% empty %}The content in the block will be rendered. In this way, we can display a friendly prompt to the user when the list is empty.

Use{% for ... empty ... %}The syntax structure is as follows:

{% for item in archives %}
    <!-- 当archives列表有内容时,这里的内容会被重复渲染 -->
    <li>
        {{item.Title}}
    </li>
{% empty %}
    <!-- 当archives列表为空时,这里的内容会被渲染 -->
    <p>目前没有找到相关内容。</p>
{% endfor %}

This design makes the code intent clearer, also greatly reduces the redundant condition judgment in the template, making our template code more concise and easy to maintain, which is in line with the concept of AnQiCMS to provide a 'simple and efficient system architecture'.

Practice Case: Taking the document list as an example

Let's take the document list of Anqi CMS as an example to demonstrate in detail{% for ... empty ... %}The practical application. Suppose we want to display the latest articles on the website and give clear prompts when there are no articles. We can usearchiveListtags to retrieve document data.

<div class="article-list">
    {% archiveList latestArticles with type="list" limit="10" %}
        {% for article in latestArticles %}
        <div class="article-item">
            <h3 class="article-title"><a href="{{article.Link}}">{{article.Title}}</a></h3>
            <p class="article-meta">
                <span>发布时间:{{stampToDate(article.CreatedTime, "2006-01-02")}}</span>
                <span>浏览量:{{article.Views}}</span>
            </p>
            <p class="article-description">{{article.Description|truncatechars:120|safe}}</p>
            {% if article.Thumb %}
                <div class="article-thumb"><img src="{{article.Thumb}}" alt="{{article.Title}}"></div>
            {% endif %}
        </div>
        {% empty %}
        <div class="no-content-message">
            <p>抱歉,当前还没有任何文章内容,敬请期待!</p>
            <p>您可以稍后再来查看,或前往其他分类浏览。</p>
        </div>
        {% endfor %}
    {% endarchiveList %}
</div>

In this example:

  1. We first use{% archiveList latestArticles with type="list" limit="10" %}The tag retrieves the most recent 10 articles from AnQiCMS and assigns the result tolatestArticlesVariable.
  2. Then,{% for article in latestArticles %}The loop starts to try to iterate through these articles.
  3. IflatestArticlesIf the list is not empty, then each one in the loop bodyarticle(Containing fields such as title, link, description, thumbnail, etc., and utilizingstampToDateFilter to format time,truncatecharsFilter to truncate description,safeFilter to prevent XSS) will be rendered as adiv.article-item.
  4. While iflatestArticlesThe list is empty, then{% empty %}The content within the block will be activated, and a message will be displayed on the page saying "Sorry, there is no article content available at the moment, please wait!This friendly prompt, rather than a blank, greatly enhances the user experience.

A deeper understanding: Why chooseemptyblock

Without{% empty %}Before the block, we might handle an empty list like this:

{% archiveList latestArticles with type="list" limit="10" %}
    {% if latestArticles %} {# 先判断列表是否为空 #}
        {% for article in latestArticles %}
            <div class="article-item">
                <h3 class="article-title"><a href="{{article.Link}}">{{article.Title}}</a></h3>
                <p>...</p>
            </div>
        {% endfor %}
    {% else %} {# 如果为空,则显示提示信息 #}
        <div class="no-content-message">
            <p>抱歉,当前还没有任何文章内容,敬请期待!</p>
        </div>
    {% endif %}
{% endarchiveList %}

Although this piece of code can achieve the same effect, it is evident that,{% for ... empty ... %}The syntax is more concise and intuitive. It combines the two closely related logical units of 'traversal' and 'handling an empty list' naturally through a label structure, avoiding additionalif-elsenested.This not only improves the readability of the template code, but also reduces the possibility of errors, which is a reflection of AnQiCMS template engine's developer-friendly and content-display responsible design.

Summary

{% for ... empty ... %}Grammar is a powerful and considerate feature of AnQiCMS template engine, allowing website operators and template developers to handle the scenario of an empty list in a more elegant and efficient way.Through this mechanism, we can not only ensure that meaningful feedback is provided to users in any situation, improve the user experience, but also make the template code itself more concise and readable.Under the empowerment of AnQiCMS, your website content management will become more skillful, whether it is rich in content or has no data, it can show a professional and smooth side.


Frequently Asked Questions (FAQ)

1. This{% empty %}block supports in all{% for %}loop usage?Yes,{% empty %}block is{% for %}the standard component of the loop, can be used in any block of the Anqi CMS template engine supported.forUsed in loops, whether it is to iterate over article lists, category lists, tag lists, or any other iterable data collection.

2. If the list contains both content andnilvalue,{% empty %}Will it be triggered?No.{% empty %}The block is triggered onlyforWhen the entire list (or slice, array) being iterated over is itself "empty", for example, it is an empty list ornilIf the list contains elements (even if the values of these elements arenilor empty strings),forthe loop will still try to iterate over these elements,{% empty %}but the block will not execute.

3. BesidesarchiveListWhat are some scenarios suitable for use{% for ... empty ... %}? {% for ... empty ... %}Applicable to all list labels that may return an empty result set. For example, when usingnavListTo get the navigation list,tagListTo get the tag list,commentListTo get the comment list,linkListUse it in a loop when getting links{% empty %}To handle empty situations, ensuring the integrity and user experience of the page.

Related articles

How to use the `IsCurrent` property to mark the currently selected filter condition in the `archiveFilters` filter tag?

As an experienced website operation expert, I deeply understand the critical role of user experience (UX) in the success of a website.A user-friendly, responsive interface can effectively guide users to discover content, and the content filtering feature is an important aspect of improving user experience.In AnQiCMS (AnQiCMS) this efficient and customizable content management system, the `archiveFilters` tag provides strong support for building flexible filtering functions, and its internal `IsCurrent` property is the 'magic wand' that lights up the user experience. Today

2025-11-06

How to determine if a custom field exists or has a value in `archiveParams` before displaying it?

As an experienced website operation expert, I deeply know the powerful potential of AnQiCMS (AnQi CMS) in content management and website optimization.The flexible content model and customizable fields provide great convenience for us to build highly personalized websites.However, how to elegantly handle these dynamically generated custom fields in template design, ensuring that they are displayed only when they exist or have a value, is the key to improving template quality and user experience.

2025-11-06

How to render different input controls (such as text, radio, checkbox) in the `guestbook` form based on the `Type` attribute?

As an experienced website operations expert, I know that a flexible and versatile content management system is the foundation of website success.AnQiCMS (AnQiCMS) with its excellent flexibility and powerful customization capabilities has become an invaluable tool in our hands.Today, let's delve deeply into a very practical topic in actual operation: how to intelligently render different input controls, such as text boxes, radio buttons, or checkboxes, in the `guestbook` form of Anqi CMS according to the preset field types in the background.This is not just an implementation at the technical level

2025-11-06

How to dynamically add a required asterisk or hint based on the `Required` property of the `guestbook` form label?

As an experienced website operation expert, I know that every detail can affect user experience and operation efficiency.When building a website, forms are an important part of interacting with users, and clear, friendly form design is the key to improving conversion rates.AnQiCMS (AnQiCMS) with its flexible template engine and powerful backend management features, has provided us with great convenience, especially in handling scenarios such as message forms that require users to fill in information.Today, let's delve deeply into a seemingly simple but extremely practical skill: how to use the `Required` field of the back-end field

2025-11-06

How to use the `if` tag in combination with `forloop.Counter` to alternate the odd and even row styles of list items?

As an experienced website operation expert, I fully understand how to enhance user experience through detailed interface design in content presentation.AnQiCMS, with its high-performance architecture based on Go language and flexible template engine, provides us with great freedom to easily implement all kinds of creativity and features.

2025-11-06

How to use the `filter-contain` filter in AnQiCMS to check string or array containment in the `if` statement?

As an experienced website operations expert, I fully understand that in an increasingly complex network environment, efficient content management and flexible page display are crucial for improving user experience and SEO effectiveness.AnQiCMS (AnQiCMS) provides a series of practical tools with its high-performance architecture based on the Go language and the powerful features of the Django template engine.

2025-11-06

How to use the `filter-divisibleby` filter to determine the divisibility of a number in an `if` statement?

In AnQiCMS template development, achieving dynamic content display and fine-grained control is a daily challenge for website operation experts.AnQiCMS is highly praised for its concise and efficient template engine, which inherits the elegant style of Django templates, making content display and logical control intuitive.In website operation, we often need to present different content or styles based on the characteristics of numbers, such as displaying an advertisement every few products or setting different background colors for odd and even rows of the list.At this time, the `divisibleby` filter can be perfectly combined with the `if` statement

2025-11-06

How to use the `filter-length_is` filter in AnQiCMS templates for `if` judgment of the exact length of a collection?

## Precise Control and Intelligent Presentation: Efficient Application of the `filter-length_is` Filter in AnQiCMS Templates In the template development practice of AnQiCMS, we often need to finely control the displayed data to ensure the accurate transmission of content and the elegant presentation of the user interface.AnQi CMS provides powerful tools for content operators and developers with its efficient architecture based on the Go language and the flexible syntax of the Django template engine, among which

2025-11-06