As an experienced CMS website operation personnel in the field of information security, I am well aware of the importance of content in attracting and retaining users.Dynamic and responsive website content display is the key to enhancing user experience, and effectively handling data sets, especially when the data may be empty, is a fundamental skill in operations.forLoop tags and theiremptyBlock is our powerful assistant for content display.

Dynamic content display andforThe core role of the loop

The template engine of AnQi CMS adopts 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 showcases, image galleries, or navigation menus.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).forThe loop becomes the foundation for traversing and displaying these data items one by one.

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 within the loop body:

{% 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 usearchiveListLabel is obtained from the security CMS when a series of article data is retrieved,archivesThe variable will contain an array of article objects. By the aboveforloop, we can easily traversearchivesEach article in theitem),and display its title, link, and description, thus constructing a dynamic article list page.

Elegant handling of empty data:emptythe practice of blocks.

In website operation, the data set may sometimes be empty.For example, there are no articles under a certain category, or there are 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.forloop tags provide a very practicalemptythe block.

{% empty %}blocks allow us toforThe collection being traversed is empty, 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.

CombineemptyblockforThe 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 %}

假设我们使用{% archiveList archives with type="page" limit="10" %}标签来获取一个分页的文章列表。如果archives变量为空,模板将不会进入{% for ... %}内部的正常展示逻辑,而是直接渲染{% empty %}Content within the block. This is more concise and elegant than manually adding{% if archives %}and{% else %}Judgment, and also more in line with the semantic design of the template

forAdvanced techniques of looping

except for the basic traversal and empty data processing, the Anqi CMS alsoforthe loop also provides some powerful auxiliary functions, making our content display more flexible:

  • forloop.Counterandforloop.RevcounterIn the loop body, we can use toforloop.Counterto get the current loop index (starting from 1), andforloop.RevcounterIt indicates the number of remaining items from the current item to the end of the loop. This is very useful for adding numbering to list items, implementing alternating row colors, 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 specifyforthe traversal order of the data in the loop.reversedIt will traverse the collection in reverse order.sortedAttempts to sort the collection (usually in the default natural order). These keywords can also be combined, for example{% for item in archives reversed sorted %}.

    {% for item in archives reversed %}
        <p>最新发布:{{ item.Title }}</p>
    {% endfor %}
    
  • cycletagsWhen we need to reuse a series of values in a loop (such as, applying CSS classes alternately to list items),cycleLabels come into play. It will output the 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 application of blocks is ubiquitous. Whether it is displaying popular articles on the homepage, all products under the category page, or the data list of custom models in the background, 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 %}This block provides friendly prompts or guidance instead of leaving users facing a blank page. This helps to enhance user satisfaction and reduce the bounce rate.
  2. Use auxiliary variables reasonably:forloop.CounterThe variables can help us achieve complex layout and style logic, reducing the workload of front-end JavaScript.
  3. Keep the code concise: Utilize{% empty %}Avoid lengthy{% if ... else ... %}Structure. In addition, for extra blank lines generated by template logic tags, you can use the-symbol to remove them, for example{%- for item in collection -%}, in order to ensure that the final rendered HTML structure is more compact

By masteringforloop and itsemptyEnglish, we can build a complete and user-friendly security CMS website, effectively supporting all content operation activities.


Common Questions and Answers (FAQ)

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

You can useforloop.CounterThe variable to obtain the current loop index, which starts from 1. Although AnQiCMS template does not directly provideforloop.Counter0you can{{ forloop.Counter - 1 }}to achieve.

2.{% empty %}Can the block handle all types of empty 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,emptyThe block will be triggered. It usually does not directly handle boolean valuesfalseor other 'empty' values of non-collection types. For these cases, you shouldforoutside the loop usage{% if ... %}logic judgment.

3. I can beforuseifDo you want to filter or conditionally display data?

Yes, it can be done completely.{% for ... %}Loops are responsible for iterating over all elements in a collection, while{% if ... %}statements can be used inside loops to process eachitemPerform conditional judgment to decide whether to display the item, or to display it in a different way. The combination of these two tags is a common practice for building complex dynamic content layouts.