If a variable's value is an array or slice, how can you use a `for` loop in a template to iterate over and output its contents?

Calendar 👁️ 73

As an experienced website operation expert, I know how important it is to efficiently display dynamic data in daily content management.AnQiCMS (AnQiCMS) leverages the powerful performance of the Go language and its flexible template system, providing us with an excellent solution.Today, let's delve deeply into a very practical and common scenario in Anqi CMS template development: how to useforLoop through an array or slice and elegantly present its content on a web page.

Loop magic in AnQi CMS template: easily loop through array and slice content.

When building dynamic websites, we often encounter the need to display a series of similar content, such as article lists, product image galleries, navigation menus, or custom parameters, etc.This content is usually organized in the form of an array (Array) or a slice (Slice).The template engine of Anqi CMS, drawing on the syntax features of mainstream templates like Django, provides us with a powerful and intuitiveforLoop tags make it easy to iterate over these data.

Core grammar: understandforThe basics of looping

The AnQi CMS template includesforLoop syntax is very intuitive, its basic structure is as follows:

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

Here, collectionIt refers to the array or slice variable you want to traverse, anditemis a temporary variable that representscollectioneach element in it. You can use it toitemThis variable, combined with the dot (.) operator, accesses the specific properties of each element. For example, ifitemrepresents an article, you may need to accessitem.Titleget the article title, oritem.LinkGet the article link.

This concise syntax design greatly reduces the threshold for template development, even without a strong programming background, operation personnel can quickly get started and realize the dynamic display of content.

In-depth Application: UnlockforMore Features of Loops

In addition to the basic traversal, Anqi CMS'sforThe loop also provides many practical auxiliary functions and advanced features to help us better control loop behavior and data display.

1. Smart handling of null data:emptyblock

Imagine if there is no article under a certain category temporarily, we do not want the page to be empty, but instead display a friendly prompt message.forrepeatedlyemptyThe block is born for this purpose. WhencollectionWhen it is empty or undefined,forThe content within the loop body will not be executed, instead,emptyBlock content.

{% for item in archives %}
    <p>文章标题:{{ item.Title }}</p>
{% empty %}
    <p>当前分类下暂无文章,敬请期待!</p>
{% endfor %}

This design makes the template logic more robust, effectively improving the user experience.

2. Master the loop state:forloopVariable

InforInside the loop, Anqi CMS provides a specialforloopA variable that contains various status information of the current loop, very suitable for performing some conditional judgments or counting operations:

  • forloop.Counter: The iteration count of the current loop (starting from 1).
  • forloop.RevcounterHow many iterations are left before the loop ends.

These counters are very convenient in practical applications. For example, you can add a special style to the first element of the list:

{% for item in navs %}
    <li class="{% if forloop.Counter == 1 %}active{% endif %}">
        <a href="{{ item.Link }}">{{ item.Title }}</a>
    </li>
{% endfor %}

Or display the current item number in the list:

{% for item in products %}
    <p>{{ forloop.Counter }}. {{ item.Name }}</p>
{% endfor %}

3. Control the traversal order:reversedwithsorted

Sometimes we want to traverse the data in a specific order.forLoop supportreversedandsortedKeyword:

  • {% for item in collection reversed %}: TocollectionReverse traversal.
  • {% for item in collection sorted %}: Try tocollectionTraverse after sorting (for sortable data types).

For example, if you want to display the latest published articles and you want them to be arranged from newest to oldest:

{% archiveList archives with type="list" order="CreatedTime desc" limit="5" %}
    {% for item in archives %}
        <p>{{ item.Title }} - {{ stampToDate(item.CreatedTime, "2006-01-02") }}</p>
    {% endfor %}
{% endarchiveList %}

(Here althougharchiveListThe tag itself supportsorderParameter, but if the data has already been loaded into a variable,sortedit can also play a role, although it is usually more efficient to specify sorting directly in the tag.)

4. Alternate display content:cycleTag

When designing list styles, we may want odd rows and even rows to have different background colors, or switch styles every few elements.cycleTags can help us achieve this alternating output requirement:

{% for item in products %}
    <div class="product-item {% cycle 'odd' 'even' %}">
        <h3>{{ item.Title }}</h3>
        {# ... 其他产品信息 ... #}
    </div>
{% endfor %}

Herecycle 'odd' 'even'They will alternate in each loopoddandevenThese strings, we can use them as CSS class names.

Flexible data source: used with filters

Anqi CMS template filters (Filters) alsoforLoops provide a rich source of data. For example, we often need to convert a comma-separated string into a list for iteration:

{% set tagsString = "SEO优化,内容营销,网站建设,Go语言" %}
{% set tagList = tagsString|split:"," %} {# 使用 split 过滤器将字符串切割成数组 #}

{% for tag in tagList %}
    <span class="tag-badge">{{ tag|trim }}</span> {# 使用 trim 过滤器去除空格 #}
{% endfor %}

BysplitA filter, we can easily convert a string into an iterable slice, and then pass throughtrimThe filter cleans each element, and finally usesforLoop through each one by one. Similarly,make_listThe filter can split a string into slices by characters,fieldsThe filter can split by spaces.

Practical case: Build a dynamic article list and image gallery

Let us experience through a comprehensive exampleforThe charm of loops in Anqi CMS templates. Suppose we want to display a list of articles, each article includes a title, a brief introduction, and if there is a cover image, it will be displayed. And each article may contain a photo gallery (this is fromarchiveDetailinImagesThe data obtained from the field).

"twig {# Retrieve article list, here using the archiveList tag, type="page" indicates support for pagination #} {% archiveList articles with type="page" moduleId="1" limit="10" %}"}

{% for article in articles %}
<div class="article-card">
    <a href="{{ article.Link }}" class="article-link">
        <h3 class="article-title">{{ forloop.Counter }}. {{ article.Title }}</h3>
        {% if article.Thumb %}
            <img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="article-thumb">
        {% endif %}
        <p class="article-description">{{ article.Description }}</p>
    </a>

    {# 获取文章详情,以获取其内部的图片列表 #}
    {% archiveDetail articleFullData with id=article.Id %}
        {% if articleFullData.Images %}
            <div class="image-gallery">
                <h4>文章图片集:</h4>
                <div class="gallery-inner">
                    {% for imgUrl in articleFullData.Images %} {# 遍历 Images 切片 #}
                        <img src="{{ imgUrl }}" alt="图片 {{ forloop.Counter }}" class="gallery-img">
                    {% endfor %}
                </div>
            </div>
        {% endif %}
    {% endarchiveDetail %}
</div>
{% empty %}
<p class="no-content-message">很

Related articles

How to directly call built-in methods (such as getting thumbnails) of a Go language struct object in a template?

As an experienced website operations expert, I am well aware of the importance of an efficient and flexible CMS system for enterprise content management.AnQiCMS (AnQiCMS) leverages its powerful performance based on the Go language and the ease of use of the Django template engine, bringing us an unprecedented degree of freedom.In daily content operations, we not only hope that the data can be displayed accurately, but also hope that these data can come alive and be intelligently processed according to different needs.Today, let's delve into a seemingly advanced but actually very practical skill

2025-11-07

How do you access the internal properties of a Go language struct (struct) object by using the dot (.) character?

## How to cleverly use the (.) operator: The art of accessing Go struct attributes in Anqi CMS templates In modern website operations, an efficient and flexible content management system is the cornerstone of success.AnQiCMS (AnQiCMS), as an enterprise-level content management platform developed based on the Go language, has won the favor of many users with its high performance, security, and powerful customization capabilities.

2025-11-07

How to correctly display dynamic data variables passed from the backend or controller to the frontend in Anqi CMS template?

As an experienced website operations expert, I have been dealing with AnQiCMS (AnQiCMS) for many years in my daily work, and I am well aware of its efficient and flexible content management features.When using Anq CMS to build and maintain websites, a core and frequently encountered requirement is how to accurately display dynamic data passed from the backend or controller in the front-end template.Today, let's delve deeply into this topic and help everyone better master the template function of AnQiCMS

2025-11-07

How to reduce the workload when updating the website theme or changing the layout using the `extends` tag?

## AnQi CMS: Use the `extends` tag to easily manage theme and layout updates, say goodbye to repetitive work Theme iteration and layout adjustment are common needs in the daily operation of a website.However, for many website managers and content operators, each such change often means a huge amount of work and potential risk of error: modifying a header may require manual editing of dozens, even hundreds, of files;Adjust a sidebar, and it's another round of massive 'copy-paste' engineering.This way of working is not only inefficient

2025-11-07

What do `{{item.Title}}` and `{{archive.Title}}` represent in different template contexts?

As an experienced website operations expert, I know that understanding the meaning and usage scenarios of template variables is crucial for efficient website operation in a content management system.AnQiCMS (AnQiCMS) provides great convenience for content display with its flexible and powerful template engine.However, beginners or users not familiar with its template mechanism often become confused about the two seemingly similar variables `{{item.Title}}` and `{{archive.Title}}`.}]

2025-11-07

How to display the current date and time in the Anqi CMS template and output them in a custom format?

As an expert with many years of experience in website operations, I am well aware of the importance of content timeliness and display professionalism to the value of the website.In an AnQiCMS content management system that is flexible and efficient, accurately controlling the display of dates and times on the page and formatting the output according to actual needs is an indispensable part of improving user experience and optimizing information delivery.Today, let's delve into how to display and format dates and times effortlessly in the AnQiCMS template.

2025-11-07

How to format time with the `now` tag, and which common Go language time formats are supported (such as year month day hour minute second)?

In the daily operation of AnQiCMS, we often need to handle various time information, whether it is to display the article publication date or dynamically display the current time on the page, an accurate and friendly format of time presentation is crucial for improving user experience and website professionalism.As an enterprise-level content management system built with Go language, AnQiCMS also inherits the unique style of Go language in time processing, especially in how the `now` tag formats time, which is worth in-depth exploration.### `now` tag

2025-11-07

How to automatically display the current year in the footer of a website (for example “© 2023”)?

As an experienced website operations expert, I am well aware of the importance of the details of website content, especially the subtle aspects such as the copyright year at the bottom of the website page, which not only concerns the professional image of the website but also indirectly affects the judgment of search engines on the freshness of the website content.In such an efficient and flexible content management system as AnQiCMS, achieving this is naturally easy.Today, let's talk about how to automatically display the current year in the footer of your website, keeping your website forever young!

2025-11-07