How to use the `for` loop tag to iterate and display list data in AnQiCMS templates?

In AnQiCMS template, dynamically displaying list data is one of the core operations for constructing rich website content. Whether it is to display the latest articles, popular products, category lists, or any custom content collection,forLoop tags are your powerful assistants. They allow you to easily traverse data and customize the display of each item as needed.

UnderstandingforThe basics of loop tags

forLoop tags are a control structure used in AnQiCMS template engine to iterate over collection data. Its basic syntax is very intuitive:

{% for 变量名 in 集合 %}
    <!-- 在这里编写您希望重复显示的内容 -->
{% endfor %}

Here,集合is the list of data you want to iterate over,变量名It represents a temporary name for the current data item in each loop. For example, if you have a list of articlesarchivesyou can use it like thisforLoop:

{% for article in archives %}
    <h3>{{ article.Title }}</h3>
    <p>{{ article.Description }}</p>
{% endfor %}

In each loop,articlethe variable will point toarchiveseach article data in the list, you can use{{ article.字段名 }}The syntax to access the various properties of the current article, such as the title,Title) and description (Description).

Get list data:forThe foundation of loops

In AnQiCMS,forThe data that loops can iterate over usually comes from various list tags, such asarchiveList(Document List),categoryList(category list),pageList(Single page list) andtagDataList(Tag-related document list) etc. These tags are responsible for retrieving and organizing data from the background, and then passing the results toforloop for rendering.

ByarchiveList(Document list) as an example, it provides a rich set of parameters to help you accurately filter and sort data. Some commonly used parameters include:

  • moduleId:Specify the document of which content model to retrieve (such as article model or product model).
  • categoryIdSpecify the category of documents to retrieve. If you want to retrieve documents from all subcategories, you can keep the default value; if you only want to retrieve documents from the current category, you can specify it explicitlychild=false.
  • limit:Control the number of documents returned, for examplelimit="10"will only display 10 items.
  • order:Define the sorting rule, for exampleorder="id desc"(Sorted by ID in reverse, i.e., the most recently published),order="views desc"(Sorted by view count in reverse order, i.e., the most popular).
  • type: Specifies the list type,type="list"Used for fixed number lists without pagination,type="page"Used for lists that require pagination (usually combined withpaginationlabel usage).

When usingforBefore the loop, you need to use these tags to get the dataset. For example, to get the list of the latest 10 articles, you can write it like this:

{% archiveList archives with moduleId="1" order="id desc" limit="10" %}
    <!-- 这里的archives变量就是for循环的数据源 -->
    {% for item in archives %}
        <!-- 循环显示文章内容 -->
    {% endfor %}
{% endarchiveList %}

In this example,archivesthat is, througharchiveListLabel gets the article data set, which is thenforUsed for looping.

Loop and display list data: practical exercise

Now we combinearchiveListandforLoop, to demonstrate how to display a list of articles.We need to display the latest 5 articles on the homepage of the website, including their titles, links, publication time, thumbnails, and summaries.

<div class="latest-articles">
    <h2>最新文章</h2>
    <ul>
        {% archiveList articles with moduleId="1" order="id desc" limit="5" %}
            {% for item in articles %}
                <li>
                    <a href="{{ item.Link }}">
                        {% if item.Thumb %}
                            <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
                        {% endif %}
                        <h3>{{ item.Title }}</h3>
                    </a>
                    <p class="summary">{{ item.Description }}</p>
                    <p class="meta">
                        发布于:{{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}
                        浏览量:{{ item.Views }}
                    </p>
                </li>
            {% empty %}
                <p>暂无最新文章。</p>
            {% endfor %}
        {% endarchiveList %}
    </ul>
</div>

In this example:

  • We usearchiveListGot the article list and named itarticles.
  • {% for item in articles %}Start the loop.itemRepresents the current article.
  • {{ item.Link }}/{{ item.Title }}/{{ item.Thumb }}Respectively obtain the article link, title, and thumbnail.
  • {% if item.Thumb %}Used to determine if there is a thumbnail, to avoid empty image tags.
  • {{ item.Description }}Display the article summary.
  • {{ stampToDate(item.CreatedTime, "2006-01-02 15:04") }}An AnQiCMS-provided function is used.stampToDateThe function is used to format the timestamp of the article's publication.
  • {{ item.Views }}It shows the page views of the article.
  • {% empty %}The block isarticlesProvide a friendly prompt when the list is empty.

Enhance user experience:forAdvanced Loop Usage

forLoops are not only for simple iteration over data, they also have some built-in special variables and modifiers to help you achieve more fine-grained control.

Loop Status Variable

InforInside the loop, there are some special variables that can help you understand the current state of the loop:

  • forloop.CounterIt represents the current loop index, starting from 1.
  • forloop.Revcounter: indicates the index of the current loop starting from the end, counted from 1.

This is very useful when you need to add special styles to the first, last, or specific elements in a list.

{% for item in articles %}
    <li {% if forloop.Counter == 1 %}class="first-item"{% endif %}>
        <!-- 内容 -->
        <p>这是第 {{ forloop.Counter }} 篇文章,距离末尾还有 {{ forloop.Revcounter }} 篇。</p>
    </li>
{% endfor %}

Loop modifier

You can also modifyforthe way a loop iterates:

  • reversed:Traverse the collection in reverse order.
  • sortedSort the set before traversing (applies to sortable sets, such as numeric or string lists).
<!-- 按发布时间从旧到新显示 -->
{% archiveList articles with moduleId="1" order="id asc" limit="5" %}
    {% for item in articles %}
        <!-- 内容 -->
    {% endfor %}
{% endarchiveList %}

<!-- 如果数据集合本身是无序的,但您想在模板中进行反向遍历 -->
{% for item in some_other_list reversed %}
    <!-- 内容 -->
{% endfor %}

Handle empty data:{% empty %}Block

When the data set you obtain may be empty, use{% empty %}The block can elegantly handle this situation instead of displaying a blank page or an error.

`html {% archiveList search_results with moduleId=“1” q=“关键字” type=“list” limit=“10” %}

{% for item in search_results %}
    <p>搜索结果:{{ item.Title }}</p>
{% empty %}
    <p>抱歉,没有找到符合您条件的文章。</p