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

Calendar 👁️ 72

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

Related articles

How does the AnqiCMS template use if/else tags for conditional judgments to dynamically display different content?

In website content operation, we often need to flexibly display different content modules or styles based on different conditions to enhance user experience and page interactivity.AnqiCMS (AnqiCMS) provides powerful template tag features, among which the `if/else` conditional judgment tags are the core tools to achieve this goal.By it, we can easily make the website content come to life according to specific rules, no longer monotonous static display.### AnqiCMS template basic conditional judgment: `if`

2025-11-09

How to implement pagination navigation in AnqiCMS templates and customize the display of page numbers and style?

In a content management system, especially when a website carries a large amount of articles, products, or other list information, reasonable pagination navigation is the key to improving user experience and facilitating content browsing.It can not only help visitors quickly find the information they need, but also avoid the slow loading caused by too long single-page content, and it is also very beneficial for search engine optimization (SEO).AnqiCMS provides a powerful and flexible template tag set, allowing you to easily implement pagination functionality on your website and customize its display style and appearance as needed.### Enable pagination feature: Starting from the list tag At

2025-11-09

How to display the AnqiCMS backend management's friend links on the front page and control the Nofollow attribute?

In website operation, friendship links are an important means to enhance website authority, attract traffic, and strengthen industry associations.However, how to effectively manage these links, especially in terms of search engine optimization (SEO), ensuring that they can play a positive role while not causing negative effects on their own website, is a concern for many operators.AnqiCMS as a content management system dedicated to providing efficient and customizable solutions offers very convenient and flexible tools in this regard.

2025-11-09

How to build and display AnqiCMS's message form on the front page, supporting custom fields and captcha?

In website operation, establishing effective interaction with visitors is a key step to improve user experience and collect valuable feedback.Anqi CMS knows this point well, therefore it provides us with a powerful and flexible feedback form function, which not only supports basic feedback collection but also allows for easy customization of fields and captcha, making the website's interactive module efficient and secure.Next, we will delve into how to build and display a fully functional comment form on the front page of Anqi CMS, supporting custom fields and captcha, thereby better serving our users.

2025-11-09

How to format a timestamp in AnqiCMS template to display a custom date and time format?

In AnqiCMS, managing website content, we often need to display the publication time, update time, or registration and login time of users, etc.These time information is usually stored in the database in the form of a timestamp, which is a series of numbers.If displayed directly on the website front end, these numbers are not intuitive and lack aesthetics.Fortunately, AnqiCMS provides very flexible template tags, allowing us to easily format these timestamps into the date and time display format we want.AnqiCMS template system

2025-11-09

How to use with or set tags in AnqiCMS templates to define variables for optimizing content display and maintenance?

In AnqiCMS template development, defining and using variables are indispensable skills to make our website content more flexible and code easier to maintain.The system uses a syntax similar to the Django template engine, where `with` and `set` tags are used to define variables, optimizing content display and managing templates effectively.Understanding and using them effectively can make your website operation twice as effective.Why do we need to define variables in the template?

2025-11-09

How to use AnqiCMS template include tag to introduce common code fragments and achieve page structure reuse?

In website content management, we often encounter situations where it is necessary to display the same content blocks, such as headers, footers, sidebars, or navigation menus, on multiple pages.If you copy and paste this code every time, it is not only inefficient, but also when you need to modify it, you have to face the繁琐 of repeated operations in multiple files.If this continues, the maintenance and updates of the website content will become extremely difficult, and inconsistencies in the experience may even occur.

2025-11-09

How to implement template inheritance using the extends tag in AnqiCMS templates to unify the visual style of the website?

In website operation, maintaining a consistent visual style is the key to brand image and user experience.Imagine if every page layout on your website was different, with navigation positions changing back and forth, users would feel confused and even lose interest.Fortunately, AnqiCMS provides a powerful and elegant way to solve this problem - that is through the `extends` tag in the template inheritance mechanism.AnqiCMS has adopted a template engine syntax similar to Django, making template development intuitive and efficient.

2025-11-09