How does the AnQiCMS template loop through arrays or objects to display list data?

Calendar 👁️ 62

In AnQi CMS template system, the core lies in understanding the Django-like template syntax, especiallyforThe application of loop tags. This mechanism makes the presentation of dynamic content intuitive and efficient, whether it is for article lists, category navigation, or product display, it can respond flexibly.

Core mechanism:forThe use of loops

Data traversal in AnQi CMS template mainly relies on{% for ... in ... %}This structure.When you get a set of data from the backend (whether it's a collection of articles, a category array, or a custom list), they are usually passed to the template as an array or an iterable object.

For example, if you get a group named by a tag such asarchiveListorcategoryList)itemsThe data, you can start your traversal like this:

{% for item in items %}
    {# 在这里,您可以访问当前循环中的每个“item”的属性 #}
    <p>数据标题:{{ item.Title }}</p>
    <a href="{{ item.Link }}">查看详情</a>
{% endfor %}

In the above code:

  • itemsThe collection of data (array or slice) you get from the backend.
  • itemis a temporary variable that represents the individual data element in the current loop iteration. In each loop,itemis automatically updated toitemsthe next element in it.
  • {{ item.Title }}and{{ item.Link }}is to access the currentitemobject that contains theTitleandLinkProperties. These property names are usually consistent with the field names you define in the Anqi CMS backend.

Common application scenarios and tag practices

The Anqi CMS provides rich tags to retrieve different types of data lists, and the data obtained by these tags is very suitable for useforloop to iterate and display:

  1. Display article or product list (archiveList) archiveListTags are a powerful tool for retrieving lists of articles, products, and other content. You can specify categories, sorting, and quantity parameters. For example, you can retrieve a list of the latest articles under a specific category:

    {% archiveList latestArticles with categoryId="1" order="id desc" limit="5" %}
        {% for article in latestArticles %}
            <div class="article-item">
                <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
                <p>{{ article.Description | truncatechars:100 }}</p> {# 截取前100个字符作为简介 #}
                <small>发布日期:{{ stampToDate(article.CreatedTime, "2006-01-02") }} 阅读量:{{ article.Views }}</small>
            </div>
        {% endfor %}
    {% endarchiveList %}
    

    here,article.DescriptionMay contain HTML, using|truncatechars:100The filter can safely extract text and avoid destroying the HTML structure.stampToDateThe filter then formats the timestamp into a readable date.

  2. Display category navigation (categoryList)When building the navigation menu or sidebar category list of a website,categoryListtags are very useful. It supports the acquisition of multi-level categories:

    <ul class="main-nav">
        {% categoryList topCategories with moduleId="1" parentId="0" %} {# 获取文章模块的顶级分类 #}
            {% for category in topCategories %}
                <li {% if category.IsCurrent %}class="active"{% endif %}>
                    <a href="{{ category.Link }}">{{ category.Title }}</a>
                    {% if category.HasChildren %} {# 判断是否有子分类 #}
                        <ul class="sub-nav">
                            {% categoryList subCategories with parentId=category.Id %} {# 获取当前分类的子分类 #}
                                {% for subCategory in subCategories %}
                                    <li><a href="{{ subCategory.Link }}">{{ subCategory.Title }}</a></li>
                                {% endfor %}
                            {% endcategoryList %}
                        </ul>
                    {% endif %}
                </li>
            {% endfor %}
        {% endcategoryList %}
    </ul>
    

    In this example, we show how to build multi-level navigation by nestingforand use loopscategory.IsCurrentto add styles to the current category.

  3. Display the site navigation menu (navList)The menu configured in the "Website Navigation Settings" can be accessed throughnavListLabel and traverse:

    <nav>
        {% navList mainNav with typeId="1" %} {# 假设typeId=1是主导航 #}
            <ul>
                {% for navItem in mainNav %}
                    <li {% if navItem.IsCurrent %}class="active"{% endif %}>
                        <a href="{{ navItem.Link }}">{{ navItem.Title }}</a>
                        {% if navItem.NavList %} {# 如果有子菜单 #}
                            <ul class="dropdown-menu">
                                {% for subNavItem in navItem.NavList %}
                                    <li><a href="{{ subNavItem.Link }}">{{ subNavItem.Title }}</a></li>
                                {% endfor %}
                            </ul>
                        {% endif %}
                    </li>
                {% endfor %}
            </ul>
        {% endnavList %}
    </nav>
    
  4. Display custom fields or image collectionsWhen your content model includes a custom image collection field (such as for displaying multiple images on an article detail page) or when you need to display a specific parameter list on the page, you can also useforLoop:

    {# 假设文章有一个名为“galleryImages”的自定义多图字段 #}
    {% archiveDetail currentArchive with name="galleryImages" %}
        {% if currentArchive.galleryImages %}
            <div class="image-gallery">
                {% for image in currentArchive.galleryImages %}
                    <img src="{{ image }}" alt="图集图片">
                {% endfor %}
            </div>
        {% endif %}
    {% endarchiveDetail %}
    
    {# 循环显示文章的自定义参数 #}
    {% archiveParams customParams %}
        <ul class="article-params">
            {% for param in customParams %}
                <li>{{ param.Name }}:{{ param.Value }}</li>
            {% endfor %}
        </ul>
    {% endarchiveParams %}
    

    Here, currentArchive.galleryImagesIt is an array of image URLs directly,archiveParamsThen return an array containing properties,NameandValueFor unified display. An array of objects with properties,

Enhanced list display: conditional judgment and auxiliary functions

During the traversal of data, you may encounter some special requirements, such as displaying different content based on conditions, numbering list items, or handling empty lists:

  • Conditional judgment (if): Pass{% if ... %}Label, you can decide whether to render specific content or apply different styles based on the value of a certain attribute of a data item.

    {% for item in articles %}
        {% if forloop.Counter == 1 %} {# 为列表中的第一个元素添加特殊样式 #}
            <li class="featured-article">
        {% else %}
            <li>
        {% endif %}
                <a href="{{ item.Link }}">{{ item.Title }}</a>
            </li>
    {% endfor %}
    

    forloop.CounterIs a special variable inside the loop, indicating the current loop number (starting from 1). Similarly,forloop.RevcounterMeans starting from the end.

Related articles

How to implement conditional logic in AnQiCMS to control the display of content?

In website operation, displaying different content based on different conditions is the key to improving user experience and achieving refined operation.AnQiCMS provides powerful and flexible template tags and logical judgment functions, allowing us to easily implement conditional display of content, thereby meeting various business needs.This article will delve into how to make use of the template engine features in AnQiCMS, controlling the display of website content precisely through conditional logic judgments.

2025-11-08

How to set and display the global information of AnQiCMS, such as Logo, filing number, and copyright?

AnQiCMS provides an intuitive and powerful way to manage and display the global information of the website, such as the website logo, filing number, and copyright statement.This information is not only an important part of the website's brand image, but also concerns the legal and compliant operation of the website.The detailed introduction on how to set and utilize these global information will follow. ### Set global information in the background All the global information of the website is concentrated in the "Global Function Settings" of AnQiCMS backend.

2025-11-08

How to display pagination links in AnQiCMS and control the number of page numbers displayed?

In website operation, effectively managing and displaying a large amount of content is the key to improving user experience.When the content list is too long, a reasonable pagination mechanism can not only make it easier for users to browse, but also optimize the page loading speed, and indirectly improve the search engine friendliness.In AnQiCMS, implementing pagination and flexibly controlling the display quantity of page numbers is a relatively direct and powerful process.--- ## Display pagination links elegantly and flexibly control the number of pages in AnQiCMS In your AnQiCMS website, when the number of articles, products, or other list content increases

2025-11-08

How to retrieve and display custom form fields in AnQiCMS comment form?

When using AnQiCMS to manage website content, the online message function is undoubtedly an important means of interacting with visitors, collecting feedback, or gathering potential customer information.In addition to the basic name, contact information, and message content, we often need to collect more specific and personalized information, such as 'Your project budget', 'The type of service you are interested in', or 'The expected contact time'.AnQi CMS provides a flexible custom message field function, allowing us to easily meet these needs.How can I retrieve and elegantly display these custom form fields on the website front page?

2025-11-08

How to format a timestamp in AnQiCMS template and display it in a specified date format?

In AnQiCMS template, processing timestamps and displaying them in a specific date format is a common requirement in content operation.No matter whether you need to display the publication time of the article or the update date of the product, understanding how to flexibly format time will greatly enhance the expressiveness of the website content.AnQiCMS provides simple and powerful template tags, making this process easy and convenient.

2025-11-08

How to define and use variables in AnQiCMS to display data flexibly in templates?

AnQiCMS (AnQiCMS) is an efficient and flexible content management system, whose powerful template function is the key to building a personalized website.In templates, defining and using variables flexibly allows us to easily handle and display various types of data, whether it's article titles, categorization information, or custom field content. All of this can be dynamically called through variables, making the website full of vitality.We will delve deeper into how to define, obtain, and use variables in AnQiCMS templates, helping everyone build and maintain websites more efficiently.

2025-11-08

How to use the template inheritance and reference feature of AnQiCMS to build reusable display modules?

When using AnQiCMS to build a website, we often encounter such situations: each page of the website has common header navigation, footer information, or some modules (such as sidebars, article recommendation lists) need to be displayed in multiple places, but the content or style may be slightly different.If you copy and paste this code every time, not only is it inefficient, but also once it needs to be modified, you have to adjust it one by one on all related pages, which is very easy to make mistakes and difficult to maintain.

2025-11-08

How to display different content and manage interfaces for multiple sites in the AnQiCMS website?

AnQiCMS, with its powerful multi-site management functions, provides an efficient and flexible solution for operators with multiple brands, sub-sites, or content branches.It allows you to easily create, manage, and display multiple independently operated websites under the same core system, greatly enhancing the efficiency of content operation.

2025-11-08