How to use the 'loop traversal tag (for)' to display a dynamic data list in AnQiCMS templates?

The website content needs to be continuously updated, such as displaying the latest articles, products, user comments, or navigation menus, etc. These dynamic data are often presented in the form of lists.In Anqi CMS, by using its powerful template engine and the intuitive 'loop iteration tag (for)', we can easily present these backend data on the website frontend, making your website full of vitality.

The template engine of AnQi CMS draws inspiration from the concise and efficient syntax of Django templates, allowing even developers with no prior experience to quickly get started.The 'loop iteration tag (for)' is the core tool we use to handle dynamic data lists, which helps us iterate through various types of data collections and display their contents one by one.

Introduction to the 'loop traversal tag (for)'

The basic syntax of the "loop through tags (for)" is very intuitive:

{% for item in collection %}
    {# 在这里显示每一个 item 的内容 #}
{% endfor %}

Here,collectionrefers to a collection containing multiple items, such as an article list, product list, or category list obtained from the backend.itemrepresents each independent data item in the set, in each iteration of the loop,itemwill be assigned the next element in the set. In this way, we can accessitemVarious properties of an object, such as{{ item.Title }}(article title) or{{ item.Link }}(article link), and display it on the page.

For a simple example, if we want to display a list of the latest articles, it might look like this:

{% archiveList archives with type="list" limit="5" %}
    {% for article in archives %}
        <div class="latest-article">
            <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
            <p>{{ article.Description }}</p>
        </div>
    {% endfor %}
{% endarchiveList %}

This code first retrieves the latest 5 articles byarchiveListtags and stores them inarchivesIn the variable. Then,forto iteratearchivesEach article in,article, and showed each article's title, link, and introduction within the loop.

Advanced usage: Make the list smarter

The 'Loop through tags (for)' is not only for simple iteration, it also provides various flexible options, making your list display more intelligent and diverse.

Skillfully handle empty data:{% empty %}温馨提示

Sometimes, the data list we obtain may be empty. In this case, if there is no prompt on the page, the user experience will be greatly reduced.forLooping{% empty %}The clause is designed for this purpose:

{% for item in archives %}
    <div class="item-display">{{ item.Title }}</div>
{% empty %}
    <p>抱歉,目前没有找到相关内容。</p>
{% endfor %}

WhenarchivesThe loop executes normally when the list is not empty; ifarchivesit is empty, then{% empty %}the content between them will be displayed, providing the user with a friendly feedback.

Customize the loop order:reversedandsortedThe magic of

You may want the list data to be displayed in a specific order.forLoop supportreversed(Reverse) andsorted(Sorted) modifier:

  • reversedReverse the order of elements in the collection. For example,{% for item in archives reversed %}.
  • sortedIs usually used to sort a list of numbers or strings in ascending order. For example,{% for item in numbers sorted %}.

This allows you to easily control the display logic of content, such as the latest content at the top, or sorted by views from high to low.

Alternating display of data:cycleThe color game of tags

When designing tables or lists, we often need to implement alternating row styles (such as different background colors).cycleTags can help you output preset values in order during each loop:

{% for item in archives %}
    <div class="row-{% cycle 'odd' 'even' %}">
        {{ item.Title }}
    </div>
{% endfor %}

Each loop,cyclewill output in sequence:'odd'and'even', adding visual hierarchy to your list.

Get loop information:forloop.Counterandforloop.Revcounter

In the loop body, you can also access some special variables to get the current state of the loop:

  • forloop.Counter: indicates the current iteration count, starting from1.
  • forloop.RevcounterThis indicates how many times are left from the current iteration to the end of the loop.总数Start counting down.

This is very useful when you need to number list items or apply specific styles based on their position:

{% for article in archives %}
    <div class="article-item {% if forloop.Counter == 1 %}featured{% endif %}">
        <span>{{ forloop.Counter }}.</span>
        <a href="{{ article.Link }}">{{ article.Title }}</a>
    </div>
{% endfor %}

Here, we have not only added a serial number to each article, but also added an extra one for the first articlefeaturedClass name.

Actual case: Dynamic data list display

The 'Loop Traversal Tag (for)' in AnQi CMS can be combined with various content tags to flexibly construct various dynamic lists.

Article List: The most common application scenario

In addition to the simple article list displayed above, we can also combine more article fields to build a richer list:

{% archiveList articles with type="page" limit="10" categoryId="1" %}
    {% for item in articles %}
    <div class="post-card">
        {% if item.Thumb %}
        <a href="{{ item.Link }}" class="post-thumbnail">
            <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
        </a>
        {% endif %}
        <div class="post-content">
            <h2 class="post-title"><a href="{{ item.Link }}">{{ item.Title }}</a></h2>
            <p class="post-excerpt">{{ item.Description|truncatechars:100 }}</p>
            <div class="post-meta">
                <span>发布于:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                <span>阅读量:{{ item.Views }}</span>
                <span>分类:<a href="{% categoryDetail with name='Link' id=item.CategoryId %}">{% categoryDetail with name='Title' id=item.CategoryId %}</a></span>
            </div>
        </div>
    </div>
    {% empty %}
    <p>此分类下暂无文章。</p>
    {% endfor %}
{% endarchiveList %}

This example shows a list of articles containing thumbnails, titles, summaries, publication times, reading counts, and categories.archiveListThe tag specifies the category ID to be retrieved as 1 and enables pagination mode.

Categories and navigation: Build multi-level menus

For the website's category menu, we usually need to display a multi-level structure. It can be easily achieved by nested usingcategoryListTags andforcycling:

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

Here, the outer loop iterates over the top-level categories, and the inner loop then determines if each top-level category has child categories (mainCat.HasChildrenIf there are any, further retrieve and traverse their subcategories to build a clear multi-level navigation structure.

Other dynamic data: Friend links, banners, etc.

forThe universality of loops means they can be used for any data provided in a list form in a CMS. For example, you can use linkListTags andforloop to display links, or use bannerListLabel display on the homepage carousel:

`twig {# Friend links list #}