How to iterate through data using the for loop tag in AnqiCMS templates and display list content on the front end?

In modern web development, content lists are everywhere, whether it is article lists, product displays, user comments, or navigation menus, they cannot do without efficient organization and presentation of data.AnqiCMS as an enterprise-level content management system based on Go language provides intuitive and powerful loop tags for template creation, allowing you to easily display various list content on the front end.

AnqiCMS's template engine adopts a design philosophy similar to Django and Blade syntax, which means it will be very quick for many who are familiar with web development. It handles logic and data display through specific tag syntax, whereforThe loop tag is one of the core features, which helps us traverse the dataset and output each item according to the preset style.

Get to know the template loop mechanism of AnqiCMS

In AnqiCMS template files, all logical controls are wrapped in{% %}tags, while variable output is used by{{ }}. When we talk about list display,forThe loop tag is the main actor. Its basic structure is very clear:

{% for item in data_source %}
    {# 在这里放置您希望对每一项数据进行展示的HTML代码 #}
    {{ item.Property1 }}
    {{ item.Property2 }}
{% endfor %}

Here, data_sourceIt is the collection of data you want to iterate over, which can be an article list, category list, etc.itemIt is a temporary variable representingdata_sourcethe current data item. Throughitem.adding the specific attribute name of the data item (for exampleitem.Title/item.LinkYou can access and display the detailed information of the data item.

Get the data source: Provide content for the loop.

To useforLoop, first you need data to loop through. AnqiCMS provides various built-in tags to help you get various types of data lists from the background and pass them asdata_sourcepass toforLoop. The most commonly used one isarchiveListTag, it is mainly used to obtain lists of documents such as articles or products.

For example, if you want to display the latest 10 articles on the homepage, you can use it like thisarchiveListTags:

{% archiveList archives with type="list" limit="10" order="id desc" %}
    {# 这里的 'archives' 就是我们将要用 for 循环遍历的数据源 #}
{% endarchiveList %}

In this example:

  • archiveListIt is used to obtain the document list tags
  • archivesIt is a custom variable name we use, which will carryarchiveListThe data set returned.
  • type="list"Indicates that we want to get a simple list, not a paginated list.
  • limit="10"Limited to fetching the latest 10 records.
  • order="id desc"It specified to sort by ID in descending order, which means the latest content is displayed first.

exceptarchiveListAnqiCMS also provides other practical list retrieval tags, such as:

  • categoryListUsed to get the category list, often used to build navigation or category trees.
  • pageListUsed to get the single-page list, such as 'About Us', 'Contact Us', etc.
  • tagListGet the list of all tags on the website.
  • tagDataListGet the list of documents related to the specified tag ID.
  • navListGet the navigation menu configured in the background.

These tags follow a similar pattern, assign the collected data set to a variable you specify, and then this variable can be used asforrepeatedlydata_source.

Traverse and display data: Build a list view

With the data source, we can combineforLoop, display content items one by one. Let's take the article list as an example to see how to display the title, link, introduction, and thumbnail of the article in a loop:

<div class="article-list">
    {% archiveList articles with type="list" limit="10" order="id desc" %}
        {% for item in articles %}
        <div class="article-item">
            <a href="{{ item.Link }}" class="article-title">{{ item.Title }}</a>
            {% if item.Thumb %}
                <a href="{{ item.Link }}" class="article-thumb">
                    <img src="{{ item.Thumb }}" alt="{{ item.Title }}">
                </a>
            {% endif %}
            <p class="article-description">{{ item.Description|truncatechars:100 }}</p>
            <div class="article-meta">
                <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02") }}</span>
                <span>浏览量:{{ item.Views }}</span>
            </div>
        </div>
        {% empty %}
        <p class="no-content">暂无文章内容。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

In this example:

  • We first usearchiveListGained the latest 10 articles and stored the data set inarticlesthe variable.
  • Then,{% for item in articles %}Start traversing this set.
  • {{ item.Link }}and{{ item.Title }}Outputted the links and titles of the articles separately.
  • {% if item.Thumb %}It is a conditional judgment, only when the article has a thumbnail will the image be displayed.{{ item.Thumb }}It will output the URL of the thumbnail.
  • {{ item.Description|truncatechars:100 }}It shows the introduction of the article and usestruncatechars:100The filter truncates it to 100 characters to avoid being too long.
  • {{ stampToDate(item.CreatedTime, "2006-01-02") }}It is a very practical time formatting function, which converts the article's creation timestamp into the familiar "year-month-day" format.
  • {{ item.Views }}It directly outputs the article's view count.
  • {% empty %}Blocks play an important role here. IfarticlesThe dataset is empty (i.e., no articles have been retrieved), thenforThe loop will not execute but will displayemptyThe content in the block greatly enhances the user experience.

Practical techniques in loops: finer control.

forLoop tags not only iterate over data but also provide some built-in variables and modifiers, allowing you to have more fine-grained control over the display of lists:

  1. forloopVariable: In each iteration,forloopThe variable will provide the current loop status information:

    • forloop.Counter: The current loop count (starting from 1).
    • forloop.Revcounter: The remaining count of the loop.

    This is very useful when you need to apply different styles to the first, last, or specific items in a list. For example, add a class to the first list item.activeClass:

    {% for item in articles %}
    <div class="article-item {% if forloop.Counter == 1 %}active{% endif %}">
        {# ... 内容展示 ... #}
    </div>
    {% endfor %}
    
  2. cycleTagWhen you need to alternate between different values in a loop (for example, to apply different background colors to adjacent list items),cyclethe tag comes in handy:

    {% for item in articles %}
    <div class="article-item {% cycle 'odd' 'even' %}">
        {# ... 内容展示 ... #}
    </div>
    {% endfor %}
    

    This will make the firstdivhaveoddClass, seconddivhaveevenClass, third and back toodd, and so on