How to use a loop (for label) to traverse and display a content list?

In AnQi CMS, whether it is to display article lists, product catalogs, navigation menus, or friend links, we will frequently deal with content lists.To dynamically display this content on the website front-end, a powerful loop function is indispensable.Today, let's delve deeper into how to use the loop in the Anqi CMS template (forTag) to traverse and display your content list.

forThe core syntax of the tag: make the content dynamic

The template syntax of AnQi CMS is similar to Django and Blade, very intuitive. When you need to handle a group of data,forTags are your helpful assistants. Their basic structure is very simple:

{% for item in collection %}
    {# 在这里显示每个item的详细信息 #}
{% endfor %}

Here, collectionIt refers to the collection of content you want to traverse, such as byarchiveListorcategoryListTags get the list of articles or categories.itemIt represents the current element of the collection in each iteration, you can accessitemto display specific content.

For example, suppose you want to display the latest several article titles and links:

{% archiveList latestArticles with type="list" limit="5" %}
    <ul class="article-list">
    {% for article in latestArticles %}
        <li>
            <a href="{{ article.Link }}">{{ article.Title }}</a>
        </li>
    {% endfor %}
    </ul>
{% endarchiveList %}

In this example,latestArticleswe go througharchiveListThe article list obtained by the tag.forthe loop,articleThe variable represents an article in each iteration. We can accessarticle.Linkthe article link byarticle.Titleaccess the article title and display it on the web page.

Loop through the content list: take the document list as an example

The document list is one of the most common dynamic content on websites. ThrougharchiveListLabel, we can easily obtain document data under articles, products and other models, thenfordisplay them in a loop.

For example, you want to display a list of documents under a category, including the title, summary, and publication time:

{% archiveList documents with categoryId="1" type="list" limit="10" %}
    <div class="documents-section">
    {% for doc in documents %}
        <div class="document-item">
            <h3><a href="{{ doc.Link }}">{{ doc.Title }}</a></h3>
            <p>{{ doc.Description }}</p>
            <p class="meta">发布时间:{{ stampToDate(doc.CreatedTime, "2006-01-02") }}</p>
            {% if doc.Thumb %}
                <img src="{{ doc.Thumb }}" alt="{{ doc.Title }}" class="document-thumbnail">
            {% endif %}
        </div>
    {% endfor %}
    </div>
{% empty %}
    <p>当前分类下没有可用的文档。</p>
{% endarchiveList %}

Here, we usearchiveListGot 10 documents under category ID 1.for doc in documentsloop:

  • doc.Linkanddoc.TitleIt provided the link and title of the document.
  • doc.DescriptionIt is used to display the introduction of the document.
  • doc.CreatedTimeIt is a timestamp, we cooperatestampToDatetags to format it as a readable date.
  • doc.ThumbThe thumbnail of the document is displayed andifThe tag determines whether an image exists.

Useful tips in the loop

To make your content display more flexible and beautiful, AnQi CMS'sforTags also provide some practical auxiliary functions.

  1. Handle empty list:emptyTagWhen your content collection may be empty,emptytags can be used. Ifforthe loop has no iterable elements.itemthenemptyThe content within the tags will be displayed, to avoid blank pages or errors.

    {% for item in someList %}
        {# 列表内容 #}
    {% empty %}
        <p>暂时没有相关内容可供显示。</p>
    {% endfor %}
    
  2. Get loop number:forloop.Counterandforloop.RevcounterInside the loop,forloop.CounterCan get the current loop number (starting from 1),forloop.RevcounterThen get the remaining number of items in the current loop. This is very useful when different styles need to be applied to specific items (such as the first or last item).

    {% for item in documents %}
        <div class="document-item {% if forloop.Counter == 1 %}first-item{% endif %}">
            <span class="item-number">{{ forloop.Counter }}.</span>
            <h3>{{ item.Title }}</h3>
        </div>
    {% endfor %}
    
  3. Adjust the traversal order:reversedandsortedSometimes you may need to display the content in a different order.reversedKeywords can allow you to traverse the collection in reverse, whilesortedKeywords can sort the collection (for sortable types).

    {# 倒序显示文章 #}
    {% for article in latestArticles reversed %}
        ...
    {% endfor %}
    
    
    {# 排序显示文章(通常结合后台排序参数更常用) #}
    {% for article in latestArticles sorted %}
        ...
    {% endfor %}
    

    However, in Anqi CMS, we usually specify sorting methods througharchiveListsuch as tags,orderparameters, which is more direct and efficient.

  4. to display different contents at intervals:cycleTagIf you want to alternate the display of different values in a loop, for example, setting different background colors for odd and even rows of a list,cycleTags are a good choice.

    {% for item in documents %}
        <div class="document-item {% cycle "odd" "even" %}">
            {# ... 内容 ... #}
        </div>
    {% endfor %}
    

    Then, the first item will getoddthe class, the second item getseventhe class, the third item goes back tooddand so on.

  5. Clean code: Remove extra blank linesTo maintain the conciseness of generated HTML, you can utilize{%-and-}Remove extra whitespace before and after tags. This is particularly useful in scenarios where a large number of elements are generated in a loop.

    {% for item in documents -%}
        <div class="document-item">
            {# ... 内容 ... #}
        </div>
    {%- endfor %}
    

Nested loop: Handling multi-level data

When dealing with multi-level classification or complex data structures, nested loops are indispensable.For example, you can traverse the top-level categories first, and then traverse the subcategories or documents belonging to each top-level category inside.

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

This example shows how to