How to iterate over an array or slice in AnQiCMS template and loop through its elements?

Calendar 👁️ 69

In the world of AnQi CMS templates, dynamically displaying content is the key to building an active and feature-rich website.Whether it is an article list, product display, navigation menu, or image gallery, we need a mechanism to traverse the data set and display each element on the page.lucky enough, Anqi CMS's template engine provides an intuitive and easy-to-use loop structure, allowing us to easily achieve this goal.

Master it easilyforLoop: The Foundation of Dynamic Content Display

The Anqi CMS template engine uses a syntax similar to Django, it goes through{% for ... in ... %}Tags are used to iterate over arrays or slices. This tag allows us to access each element in the data collection one by one and display their content as needed.

Imagine you have a set of the latest articles or a series of products to display. ThroughforLoop, you can let the template automatically handle these data without manually adding them one by one. The basic usage is very simple and clear:

{% for item in collection %}
    {# 在这里,'item' 代表'collection'中的每一个元素 #}
    {# 我们可以通过 'item.属性名' 来访问元素的具体数据 #}
    <p>{{ item.Title }}</p>
{% endfor %}

Here, collectionIt is an array or slice containing multiple elements, anditemThis is a temporary variable, which is assigned a value in each loopcollectionOf the current element. Next, we will delve deeper into how to flexibly use the Anqi CMS template through several real-life scenariosforLoop.

Scenario one: Building article or product lists

This is the most common dynamic content display requirement. Suppose we want to display the latest articles on a webpage. Anqi CMS providesarchiveListThe tag to get article data. We can use it like this:

{% archiveList latestArticles with type="list" limit="5" %}
    <ul class="article-list">
        {% for article in latestArticles %}
            <li>
                <a href="{{ article.Link }}" title="{{ article.Title }}">
                    <h3>{{ article.Title }}</h3>
                    <p>{{ article.Description }}</p>
                    <span>发布于:{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
                </a>
                {% if article.Thumb %}
                    <img src="{{ article.Thumb }}" alt="{{ article.Title }}">
                {% endif %}
            </li>
        {% endfor %}
    </ul>
{% endarchiveList %}

In this example,archiveListThe tag got the latest 5 articles and assigned them to:latestArticlesthe variable. Subsequently, we use{% for article in latestArticles %}To iterate over the article collection. Inside the loop,articleThe variable represents each article, we can access and display the title, link, summary, publication time, and thumbnail of the article througharticle.Link/article.Title/article.Description/article.CreatedTimeandarticle.Thumbthese properties, easily accessing and displaying the title, link, summary, publication time, and thumbnail of the article.stampToDateThe filter helps us format timestamps into readable dates.

Scenario two: Implementing a multi-level navigation menu.

The website's navigation menu usually contains multiple levels, such as submenus under the main menu. Anqi CMS'snavListLabels can retrieve navigation data, and each returned navigation item may contain aNavListattribute indicating its submenu. This is where nestedfor loops really come into play:

{% navList mainNav %}
    <nav class="main-navigation">
        <ul>
        {% for item in mainNav %}
            <li class="{% if item.IsCurrent %}active{% endif %}">
                <a href="{{ item.Link }}">{{ item.Title }}</a>
                {% if item.NavList %} {# 检查当前导航项是否有子导航 #}
                    <ul class="sub-menu">
                    {% for subItem in item.NavList %}
                        <li class="{% if subItem.IsCurrent %}active{% endif %}">
                            <a href="{{ subItem.Link }}">{{ subItem.Title }}</a>
                        </li>
                    {% endfor %}
                    </ul>
                {% endif %}
            </li>
        {% endfor %}
        </ul>
    </nav>
{% endnavList %}

Here, the outer loop traverses all top-level navigation items, while the inner loop{% if item.NavList %}When the condition is true, traverse the sub-navigation of the current top-level navigation item.This nested structure allows us to flexibly build multi-level navigation menus of any depth, perfectly adapting to the structural requirements of the website.

Scenario three: display a group of images or a gallery

In many cases, an article or product may be associated with multiple images to form a collage or gallery. In AnQi CMS,archiveDetailorcategoryDetailtags are used to filter byname="Images"When obtaining parameters, you can directly return a slice of an image URL. Traverse this slice to easily build an image display:

{% archiveDetail productImages with name="Images" %}
    {% if productImages %} {# 确保有图片数据 #}
        <div class="product-gallery">
            {% for imageUrl in productImages %}
                <img src="{{ imageUrl }}" alt="产品图片展示">
            {% endfor %}
        </div>
    {% endif %}
{% endarchiveDetail %}

Here, productImagesThe variable directly contains the picture URL slice. We do not need any additional processing, just use{% for imageUrl in productImages %}We can extract the picture links one by one and render them into<img>Tags to achieve a simple image gallery.

MasterforAdditional techniques for loops

In addition to the basic traversal functions, the Anqi CMS'sforLoops also provide some practical auxiliary features to make content display more flexible:

  • Handle empty data:{% empty %}When your data set may be empty, use:{% empty %}Labels can elegantly display a tip message,

Related articles

How to implement scheduled publishing of articles in AnQiCMS to ensure that content is visible on the front page at specified times?

As a content operator, we know that in the age of information explosion, the timing of content release often determines its dissemination effect.In order to coordinate with market activities, maintain a stable update frequency, or publish important announcements at specific times, a function that can accurately control the publication time is indispensable.AnQiCMS (AnQi Content Management System) is well-versed in this, providing us with a simple and powerful scheduling mechanism to ensure that every meticulously prepared article is presented to the reader at the most appropriate time.Use AnQiCMS for timed publishing

2025-11-09

How to customize parameters in the AnQiCMS backend and display them in the front-end template?

During the operation of a website, we often encounter such needs: standard content fields (such as title, content, publication time) can no longer meet the needs of personalized display.For example, a product detail page may need to display "production dateAnQiCMS as a flexible enterprise-level content management system fully considers these customized needs.

2025-11-09

How to build and display the breadcrumb navigation of the current page using the `breadcrumb` tag in AnQiCMS?

In website operation, breadcrumb navigation (Breadcrumb Navigation) is an important element to enhance user experience and website structure clarity.It not only helps visitors quickly understand the position of the current page in the website hierarchy, but also effectively assists search engines in understanding the relationship between website content, and has a positive effect on SEO optimization.For AnQiCMS users, building and displaying breadcrumb navigation is a very convenient operation, thanks to the powerful template tags built into AnQiCMS.### Understand AnQiCMS's

2025-11-09

How to use the `if` tag in AnQiCMS templates for conditional judgment to control content display?

When managing content in AnQi CMS, we often need to display different information based on different situations.For example, a blog post may have a thumbnail, while another does not; or a module may only display under certain conditions.At this time, flexibly using the conditional judgment in the template, that is, the `if` tag, can help us achieve these dynamicized content display needs.The AnQi CMS template engine supports syntax similar to Django, where the `if` tag is the core tool for conditional judgments.

2025-11-09

How to define variables and display their values in AnQiCMS templates?

In AnQiCMS templates, we often need to handle various data, whether it is the name of the website, the title of the article, or the product details, these dynamic contents all need to be carried and displayed through variables.Understanding how to define and display variables in templates is the core of AnQiCMS template development.AnQiCMS adopts a syntax similar to the Django template engine, making the use of variables intuitive and easy to pick up.In the template file (usually in `.html` format, stored in the `/template` directory)

2025-11-09

How to set up an independent template for a single page in AnQiCMS and display its content correctly?

In AnQiCMS, single pages (such as "About Us", "Contact Information", or specific product landing pages) are an important part of our website content.They usually carry unique information and need to have a different layout and visual style from other content on the website (such as article lists or product details).Fortunately, AnQiCMS provides极高的flexibility, allowing you to easily set up a dedicated independent template for each single page, thereby creating a unique user experience.### AnQiCMS template base

2025-11-09

How does the AnQiCMS website achieve fast content display under high concurrency through static caching and Go language features?

In today's rapidly changing digital world, the speed of website access and stability under high concurrency have become key factors in user experience and search engine rankings.For a content-rich corporate website or self-media platform, ensuring that content is presented quickly while efficiently utilizing server resources is a major challenge for operators.AnQiCMS (AnQiCMS) with its powerful core based on the Go language and the exquisite static caching mechanism, provides an excellent solution to this problem.### Go Language Empowerment

2025-11-09

How to convert the case of a string and display it in AnQiCMS template?

In website content operation, we often encounter the need to format text.In order to unify the brand image, improve the readability of the page, or optimize the search engine friendliness, converting strings to uppercase and lowercase is a fundamental and practical skill.AnQiCMS as an enterprise-level content management system developed based on the Go language, with its flexible template engine syntax (similar to Django templates), provides us with a rich set of tools to accurately control the display of content.Today, let's delve deeply into how to use AnQiCMS

2025-11-09