How to iterate over list data in a template and display it one by one?

Calendar 81

In AnQi CMS, managing and displaying content is one of its core advantages.When we need to display dynamic list data on the front end of a website, such as the latest articles, popular products, and content collections under categories, understanding how to efficiently iterate through these data in templates and display them one by one is an indispensable skill for website operators and template developers.

The Anqi CMS template system adopts a syntax similar to Django, which is intuitive and powerful, making the transformation of technical information and practical application extremely convenient.

Core loop syntax:{% for %}Tag

In AnQi CMS templates, the main tool for iterating over list data is:{% for ... in ... %}Loop tags. Their basic structure is very clear:

{% for item in list_data %}
    {# 在这里放置你想要为每个列表项显示的内容 #}
    {{ item.Field1 }}
    {{ item.Field2 }}
    {# ...更多字段... #}
{% endfor %}

here,list_dataRepresents the list data source you need to iterate over, anditemis the temporary variable for the current list item in each iteration. You can name it anything you like, for exampleitem.article/product/categoryto enhance code readability.

This loop label must be closed with.{% endfor %}to indicate the end of the loop block.

Data source: the bridge from backend to template.

Our company's CMS provides various tags to obtain different types of data lists, they are{% for %}The data source in loop:

  1. Document list (archiveList)This is the most commonly used one, used to obtain document data such as articles, products, etc. For example, to display the latest 10 articles, you can get the data like this:

    {% archiveList archives with type="list" limit="10" order="id desc" %}
        {# 在这里遍历 'archives' 变量 #}
    {% endarchiveList %}
    

    HerearchivesIt is what we areforcan be used in the looplist_data.archiveListTags provide rich parameters for filtering and sorting data, such as:

    • moduleIdSpecify the content model ID (for example, article model ID is 1, product model ID is 2).
    • categoryIdFilter content based on category ID.
    • limitControl the number of displays, also can use."offset,limit"Skip the previous data in the form.
    • typeSpecify the list type,"list"Used for normal lists,"page"Used for paginated lists (to be used withpaginationtags).
    • orderSpecify the sorting method, such as"id desc"(Descending by ID, i.e., most recent).
  2. Category list (categoryList)If you need to display the website's classification structure, such as the navigation menu or the sidebar on the classification page,categoryListtags are very useful:

    {% categoryList categories with moduleId="1" parentId="0" %}
        {# 在这里遍历 'categories' 变量 #}
    {% endcategoryList %}
    

    moduleIdused to specify the content model of the classification,parentId="0"Used to obtain the top-level category.

In addition to the above two, Anqi CMS also providespageList(Single-page list),tagList(Tag list),linkList(Friend links),navListtags such as (navigation list), which also follow{% SomeList list_var %} ... {% endSomeList %}structure, allowing you to easily obtain various data.

Retrieve and display the details of the list item

Once you pass{% for item in list_data %}Enter the loop,itemThe variable represents the current list item being processed. You can access.by using the operatoritemVarious properties (fields). These fields are usually related to the fields you fill in when managing content in the background, for example:

  • {{ item.Title }}: Displays the title of the current item.
  • {{ item.Link }}: Displays the link of the current item.
  • {{ item.Description }}: Display the current item's introduction.
  • {{ item.Thumb }}or{{ item.Logo }}: Display the thumbnail or cover image of the current item.
  • {{ item.Views }}: Display the number of views of the current item.
  • {{ item.CreatedTime }}: Display the creation time of the current item.

It is worth noting that,CreatedTimeThis timestamp field is provided by Anqi CMSstampToDateA filter that can format it into a more readable date and time. For example, to format a timestamp into the format “Year-Month-Day”, you can write it like this:{{ stampToDate(item.CreatedTime, "2006-01-02") }}

If a field in a list item may contain HTML content (such as part of the HTML in an article detail), in order to ensure that these HTML is parsed correctly rather than displayed as plain text, you need to use|safeFilter:{{ item.Content|safe }}

Handle empty data:{% empty %}The Art of Elegance

Imagine if your list data source is empty due to certain conditions, but you don't want the page to be left blank. At this point,{% for %}label's{% empty %}The clause comes in handy. It allows you to display a friendly prompt when the list is empty:

{% for item in archives %}
    {# 列表有数据时显示的内容 #}
{% empty %}
    <p>抱歉,目前没有相关内容可供显示。</p>
{% endfor %}

Practical case: Build a content list

Below, let's go through a common article list example to see how these concepts can be combined:

<div class="article-list">
    {% archiveList latestArticles with type="list" moduleId="1" limit="5" order="id desc" %}
        {% for article in latestArticles %}
        <div class="article-item">
            <a href="{{ article.Link }}" title="{{ article.Title }}">
                {% if article.Thumb %} {# 判断是否有缩略图 #}
                <img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="article-thumb">
                {% endif %}
                <h3>{{ article.Title|truncatechars:30 }}</h3> {# 截取标题到30个字符 #}
            </a>
            <p class="article-description">
                {{ article.Description|truncatewords:50 }} {# 截取简介到50个单词 #}
            </p>
            <div class="article-meta">
                <span>发布于: {{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
                <span>阅读量: {{ article.Views }}</span>
                {% comment %} 假设Category是另一个需要获取详情的标签 {% endcomment %}
                <span>分类: <a href="{% categoryDetail with name='Link' id=article.CategoryId %}">{% categoryDetail with name='Title' id=article.CategoryId %}</a></span>
            </div>
        </div>
        {% empty %}
        <p>目前还没有任何文章发布。</p>
        {% endfor %}
    {% endarchiveList %}
</div>

In this example, we show:

  • How

Related articles

How to use conditional judgment logic in a template to control the display and hiding of content?

In the presentation of website content, we often need to decide based on different situations which information should be displayed to visitors and which should be temporarily hidden.AnQiCMS (AnQiCMS) provides flexible template conditional judgment logic, making content display and hide intuitive and efficient.By these judgments, you can easily implement personalized page layouts, content display under permission control, and adjustment of page elements based on data status, which greatly enhances the dynamicity and user experience of the website.The Anqi CMS template system uses a syntax similar to the Django template engine

2025-11-08

How to display breadcrumb navigation on the page to enhance users' understanding of the content structure?

When we browse websites, we often see a line of text at the top or above the content area, clearly indicating the position of the current page within the overall website structure, like "Home > Product Center > Some Product Category > Some Product Detail" and so on.This is what we commonly refer to as 'Breadcrumb Navigation'.It can not only help users quickly understand the content hierarchy of the website, avoid getting lost, but also play an important role in user experience and search engine optimization (SEO).Aq CMS fully understands the importance of breadcrumb navigation

2025-11-08

How to build and display a multi-level navigation menu for a website?

Website navigation, like the skeleton and compass of a website, it guides visitors to explore the website content, and is the core of user experience and information architecture.A clear and accessible navigation menu that not only helps users find the information they need quickly, but is also crucial for search engine optimization (SEO).AnQiCMS (AnQiCMS) is well-versed in this, providing powerful and flexible navigation management features that allow you to easily build and display multi-level navigation menus.Next, we will delve deeper into how to build and display your website navigation step by step in Anqi CMS.--- ### One

2025-11-08

How to dynamically display SEO titles, keywords, and descriptions (TDK) on different pages?

In website operation, Search Engine Optimization (SEO) is a key element in enhancing website visibility.Among them, the page title (Title), keywords (Keywords), and description (Description), abbreviated as TDK, play a crucial role.They are not only the primary information that search engines understand the content of the page, but also an important factor in attracting users to click.In AnQiCMS (AnQiCMS), we can easily implement the dynamic display of TDK, allowing each page of the website to have appropriate and attractive TDK information

2025-11-08

How to format timestamps and display them on the page as a readable date and time?

In website operation, the timeliness of content is often the key to attracting readers' attention.Whether it is the release date of the article or the update time of the product, these pieces of information, if presented in a clear and easy-to-understand manner on the page, will greatly enhance the user experience.However, you may find that the time information recorded by AnQiCMS backend, when directly called in the template, often appears as a long series of numbers, which is what we usually call a timestamp.These original timestamps are convenient for internal system processing, but they lack readability for ordinary users.It's lucky that

2025-11-08

How to set the recommendation attribute to affect the display priority of the front-end content when publishing a document?

How to effectively guide visitors to focus on key information when managing content in AnQi CMS, and enhance the visibility and interactivity of the content, is a common concern for operators.By setting the recommended properties of the document reasonably, we can finely control the display priority of the front-end content, thereby achieving this goal.This not only helps to optimize the user experience, but also better serves the overall operation strategy of the website.### Backend settings recommended attribute: clear content positioning When we publish or edit a document, the content editing interface of Anqi CMS provides a feature area named "Recommended Attribute".

2025-11-08

How to customize the document URL alias to optimize its display in browsers and search results?

In website operation, a URL (Uniform Resource Locator) is not only the address of the content, but also the first step for users and search engines to recognize the website.A clear, meaningful, and friendly URL alias that can greatly enhance the display effect of content in the browser and achieve better visibility in search results.AnQiCMS provides flexible and powerful features, allowing us to easily customize documents, categories, tags, and even the URL aliases of the page itself, thereby optimizing the overall performance of the website.Why is it important to use custom URL aliases?Firstly, for search engines

2025-11-08

How to use the scheduled publishing feature to automatically go live and display documents at specified times?

## Precisely Control Content Rhythm: A Practical Guide to AnQi CMS Scheduled Publishing Function In today's increasingly refined content operation, how to ensure that content reaches the target audience at the most appropriate time is a core challenge faced by every operator.Manually publishing is inefficient and is prone to delays or errors due to temporary affairs or time differences.Fortunately, AnQi CMS provides a powerful and practical feature - scheduled publishing, which can make content going live automated and precise, bringing unprecedented flexibility and efficiency to website operations.The timing release function of Anqi CMS, as the name implies

2025-11-08