How to traverse an array or list and output each item on the page?

In the template development of Anqi CMS, effectively traversing and outputting arrays or lists is a core skill for building dynamic and rich content pages.As an experienced CMS operation personnel in the field of information security, I am well aware of the importance of flexibly using template tags for content presentation.The security CMS adopts a syntax similar to Django template engine, making content loops and conditional judgments intuitive and powerful.

Auto CMS template engine's loop mechanism

In the template design of AnQi CMS,forLooping through tags is a key tool for processing array or list data.It allows us to access each item in the collection one by one and display the data of each item on the page.forLoops are indispensable foundations.

When we need to traverse a list or array provided by Auto CMS, we use{% for item in collection %}such a structure. Here,collectionrepresents the array or list variable that needs to be traversed, whereasitemis the temporary variable for the current item in each iteration. Inside the loop body, we can use{{ item.属性名 }}to access the various data of the current project. For example, to output the title of each article in the article list, we can define aarchivesvariable to receive the article list, then use{{ item.Title }}Get the title.

Basic Traversal and Output Practice

Assuming we want to display the latest ten articles on the homepage. We can usearchiveListtags to get the list of articles and assign it to a variable, such asarchives。Then, throughforto process and output the titles and links of these articles one by one.

Here is a typical example:

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

In this example,archivesReceived the latest ten articles.articleThe variable represents the current article in each loop, and we can convenientlyarticle.Link/article.Titleandarticle.Descriptionaccess its properties, and usestampToDateto format timestamps.

the application of loop auxiliary variables

To achieve finer control or display in loops, Anqi CMS provides several built-in loop helper variables.forloop.CounterYou can obtain the current loop index (starting from 1), andforloop.RevcounterIt represents the number of remaining elements in the current loop. These variables are very useful when it is necessary to distinguish the first, last, or for numbering display.

For example, if we want to add a special style to the first element of the list:

<ul class="product-list">
    {% archiveList products with type="list" moduleId="2" limit="5" %}
        {% for product in products %}
            <li class="product-item {% if forloop.Counter == 1 %}featured{% endif %}">
                <a href="{{ product.Link }}">{{ forloop.Counter }}. {{ product.Title }}</a>
            </li>
        {% endfor %}
    {% endarchiveList %}
</ul>

Here,forloop.Counter == 1Determine if the current element is the first element of the loop, if it is, then addfeaturedClass. Also, we output the element's index.

An elegant way to handle empty sets.

In actual content display, a list or array may be empty at times. To avoid blank pages or errors, the security CMS providesfora loop that provides{% empty %}tags to handle this situation. WhenforThe collection being traversed by the loop is empty.{% empty %}The content within the tag will be rendered.

This allows us to provide users with friendly prompt messages instead of an empty page:

<div class="category-articles">
    {% archiveList categoryArchives with type="page" categoryId="当前分类ID" limit="10" %}
        {% for item in categoryArchives %}
            <div class="article-preview">
                <h3><a href="{{ item.Link }}">{{ item.Title }}</a></h3>
                <p>{{ item.Description }}</p>
            </div>
        {% empty %}
            <p>该分类下暂无文章,敬请期待!</p>
        {% endfor %}
    {% endarchiveList %}
</div>

Through this method, even thoughcategoryArchivesNo data, the page can also display the preset prompt information, improving the user experience.

Advanced loop operations and data processing

Anqi CMS'sforThe loop also supportsreversedandsortedModifiers, used to change the order of iteration.reversedCan reverse iterate over a list,sortedthen try to sort sortable elements (e.g., numeric lists). In addition,cycleThe label allows us to alternate a series of predefined values within a loop, which is very convenient when alternating styles or content.

For example, sort articles by publication time in reverse order, or sort by ID:

<ul class="sorted-list">
    {% archiveList allArchives with type="list" limit="5" order="created_time desc" %} {# 假设 order 语法支持created_time desc #}
        {% for item in allArchives reversed %} {# 反向遍历 #}
            <li>{{ item.Title }}</li>
        {% endfor %}
    {% endarchiveList %}
</ul>

<ul class="cycled-list">
    {% categoryList categories with moduleId="1" parentId="0" limit="3" %}
        {% for category in categories %}
            <li class="{% cycle 'even' 'odd' %}" >{{ category.Title }}</li> {# 轮流输出even或odd #}
        {% endfor %}
    {% endcategoryList %}
</ul>

sortedKeywords are usually used to sort lists of numbers or strings. Although the documentsortedexamples are forint,but in practical use, ifcollectionis a sortable list, it will try to sort.

Examples of practical application scenarios

In AnQi CMS, the traversal of arrays or lists is everywhere.

  • Multi-level navigation menu:Through nestingcategoryListTags andforLooping, you can build multi-level navigation menus with unlimited depth, perfectly matching complex website structures.
  • Product Parameters DisplayWhen a product has multiple custom parameters (such as color, size), these parameters are stored in an array, and you can usearchiveDetailto get these parameters, and thenforloop through them one by one to display.
  • Image gallery or carousel: If a certain content (article, product, single page) has multiple images, it is usually stored in array form. UtilizearchiveDetailto obtain the image array (such asImagesfield), and then combineforLoop output<img>Tag, and you can build a gallery or carousel.

For example, get the image group of the article and display it:

<div class="gallery">
    {% archiveDetail currentImages with name="Images" %}
    {% for imgUrl in currentImages %}
        <img src="{{ imgUrl }}" alt="图片描述" />
    {% endfor %}
    {% endarchiveDetail %}
</div>

ThisforThe flexibility of loops allows the AnQi CMS to easily meet various content display needs, whether it is a simple list or a complex data structure, an efficient solution can always be found.

Summary

Master the array or list traversal techniques in the Anqi CMS template, which is the key to building an efficient and flexible website.forLoops and their rich auxiliary variables and modifiers provide powerful content display capabilities for website operators.By reasonably using these tags, we can present the data of the backend management in the front-end page in the most user-friendly manner, thereby enhancing user experience and content attractiveness.

Common Questions (FAQ)

1. How toforIn the loop, how do you determine whether the current element is the first or last?

In the Anqi CMS.forIn a loop, you can use built-inforloop.Counterandforloop.Revcountervariables to judge.forloop.CounterThe counting starts from 1, therefore{% if forloop.Counter == 1 %}you can judge if it is the first element.forloop.RevcounterRepresents how many elements are left until the end of the list, when{% if forloop.Revcounter == 1 %}is true, it means that the current is the last element.

2. How can I nest loops in a loop to process multi-level data structures, such as multi-level categories?

The template engine of AnQi CMS supports nested loops.You can get an element containing a sublist by accessing it in the outer loop, and then iterate over this sublist in the inner loop.categoryListto get the first-level category in the outer loop, and then call it again in the inner loopcategoryListand pass inparentIdFor the current first-level category,Id.

{% categoryList mainCategories with moduleId="1" parentId="0" %}
    <ul>
        {% for mainCat in mainCategories %}
            <li>
                <a href="{{ mainCat.Link }}">{{ mainCat.Title }}</a>
                {% if mainCat.HasChildren %}
                    {% categoryList subCategories with parentId=mainCat.Id %}
                        <ul>
                            {% for subCat in subCategories %}
                                <li><a href="{{ subCat.Link }}">{{ subCat.Title }}</a></li>
                            {% endfor %}
                        </ul>
                    {% endcategoryList %}
                {% endif %}
            </li>
        {% endfor %}
    </ul>
{% endcategoryList %}

How do I traverse and display an array type field of a custom model on the page (for example, multiple images)?

For fields set as array type (such as image group) in custom modelsImagesor other custom group image fields), you can first usearchiveDetailLabel gets the value of this array field, then assigns it to a variable, and then performs operations on this variable.forLoop traversal.

{% archiveDetail allImages with name="Images" %} {# 获取当前文档的所有图片,并赋值给allImages变量 #}
<div class="image-gallery">
    {% for imageUrl in allImages %}
        <img src="{{ imageUrl }}" alt="图片展示" class="gallery-image" />
    {% endfor %}
</div>
{% endarchiveDetail %}

Here,allImagesThe variable contains an array of image URLs.forLoop and output each image one by onesrcproperties.