How to use for loop to traverse list data in the template and display it?

Calendar 👁️ 50

In website content management, dynamically displaying list data is a very basic and important feature.Whether it is a news list, product display, category navigation, or friend links, we need to be able to flexibly retrieve data from the backend and present it on the front-end template.AnQiCMS (AnQiCMS) provides a powerful and easy-to-use template engine, allowing us to easily meet these requirements, among which the "for loop" is the core tool for displaying list data.

AnQiCMS's template engine adopts a syntax style similar to Django, which allows users with web development experience to quickly get started.When we talk about a "for loop", it allows us to iterate over the array or collection data passed from the backend to the frontend item by item, and to process and display each item independently.

Start the journey of data traversal:forBasic usage of the loop

The most commonforA loop form, it looks like this:{% for item in your_list %}. Here,your_listIt represents the list data you get from the backend, whileitemit is a temporary variable that automatically points to in each loopyour_listThe current item of data. When the loop ends, we need to use{% endfor %}to close the loop block.

For example, if we have a file namedarchivesThe article list data, if you want to display their titles and links on the web page, we can write the template code like this:

<ul>
    {% for article in archives %}
    <li><a href="{{ article.Link }}">{{ article.Title }}</a></li>
    {% endfor %}
</ul>

In this example,articleIt is the one we define in the loopitemby using the form of the variable,article.Linkandarticle.TitleWe can then get the link and title of each article, thus dynamically generating a list.

In addition, to better control the display of the list,forLoops also provide some practical built-in variables, which can be found inforloopthe object:

  • forloop.Counter: indicates the current iteration number of the loop, starting from 1.
  • forloop.Revcounter: Indicates the remaining number of iterations in the current loop.

Using these counters, we can easily add special styles to the first or last item in the list, or make other logical judgments.

Adaptability:forAdvanced use of loops

In practical applications, the display of list data is often not immutable, AnQiCMS providesfora variety of modifiers and tags to deal with different scenarios.

Handle empty data:{% empty %}Tag

Sometimes, the data list you get from the background may be empty.If you loop an empty list directly, nothing will be displayed on the page, which may confuse the visitor.To provide a more friendly user experience,forLoop support{% empty %}tags. Whenforthe list being traversed by a loop is empty,{% empty %}The content within the block will be displayed, not the loop itself.

<ul>
    {% for product in products %}
    <li>
        <img src="{{ product.Thumb }}" alt="{{ product.Title }}">
        <h3>{{ product.Title }}</h3>
    </li>
    {% empty %}
    <li>抱歉,暂时没有产品信息可供显示。</li>
    {% endfor %}
</ul>

Change the order of the loop:reversedandsortedModifier

You may need to display the list in reverse order or simply sort the list items. AnQiCMSforLoop supportreversedandsortedmodifier:

  • {% for item in list reversed %}: Traverse the list in reverse.
  • {% for item in list sorted %}Translate the list to default sort and traverse (usually in dictionary order of numbers or strings).

For example, to display the latest published articles at the top of the list, but the background data is stored in ascending order by ID, you can usereversed:

{% for news in news_list reversed %}
    <p>{{ news.Title }} - {{ stampToDate(news.CreatedTime, "2006-01-02") }}</p>
{% endfor %}

to achieve alternating styles:cycleTag

In some designs, you may need list items to display alternating styles, such as different colors for odd and even rows.cycleThe label provides a perfect solution. It allows you to define a series of values, each time looping through and using a value in order, until all values are exhausted and then starting over from the beginning.

{% for item in my_items %}
    <div class="{% cycle 'even-row' 'odd-row' %}">
        {{ item.Content }}
    </div>
{% endfor %}

Thus,my_itemsThe first item in the list will be usedeven-rowThe second item will be usedodd-rowThe third item will be used againeven-rowand so on.

Combined with the actual application of AnQiCMS built-in tags

AnQiCMS built-in a variety of practical tags to help you get various types of data lists, and then you can combineforto display them in a loop.

to display the article list(archiveList)

archiveListTags are powerful tools for obtaining lists of articles or documents. You can filter and retrieve data according to various conditions such as category ID, module ID, recommended attributes, sorting methods, and more.

<h3>最新文章</h3>
<ul>
    {% archiveList latest_articles with type="list" limit="5" order="id desc" %}
    {% for article in latest_articles %}
    <li>
        <a href="{{ article.Link }}">{{ article.Title }}</a>
        <span>发布于:{{ stampToDate(article.CreatedTime, "2006-01-02") }}</span>
        <span>阅读量:{{ article.Views }}</span>
    </li>
    {% empty %}
    <li>暂无最新文章。</li>
    {% endfor %}
    {% endarchiveList %}
</ul>

Display category list(categoryList)

If you need to build a navigation menu or sidebar category,categoryListLabel collaborationforLooping will be very convenient. It even supports nested looping display for multi-level categories.

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

Display friend links(linkList)

For the link at the bottom of the website,linkListthe tag can directly obtain the link data configured in the background, and thenfordisplay in a loop.

<div class="friend-links">
    <h4>友情链接</h4>
    {% linkList friends %}
    {% if friends %}
    <ul>
        {% for link in friends %}
        <li><a href="{{ link.Link }}" {% if link.Nofollow == 1 %}rel="nofollow"{% endif %} target="_blank">{{ link.Title }}</a></li>
        {% endfor %}
    </ul>
    {% else %}
    <p>暂无友情链接。</p>
    {% endif %}
    {% endlinkList %}
</div>

Note on image processing

When displaying list items in a loop, especially when it involves images, you may encounter issues with image addresses or thumbnails. From AnQiCMS'sarchiveListorcategoryListtags returned byitemObjects usually containitem.Thumboritem.LogoSuch properties directly provide the image path. If you need to perform additional processing on the image, such as obtaining thumbnails or using lazy loading, you may need to work with other filters or HTML attributes, such aslazy="data-src"Set the image lazy loading attribute.

Keep the template tidy and efficient: **Practice

Good habits in template development can greatly improve efficiency and code maintainability.

  • Reasonably name variables:InforIn the loop, assign aitemChoose a meaningful name (for examplearticle/category), which makes the code more readable.
  • Utilize|safeFilter:If the content you loop to output contains HTML code (such as the article content field), in order to prevent HTML tags from being escaped into plain text, remember to use|safeFilter, for example{{ article.Content|safe }}.
  • Optimize the template structure:Consider using for code blocks that are reused{% include "partial/header.html" %}Translate auxiliary labels into separate files and then import them where needed, which will make your template structure clearer and easier to maintain.
  • Performance consideration: Although AnQiCMS's template tags have been optimized a lot, but in designing complexforWhen looping and nesting, it is still necessary to avoid unnecessary repeated data queries and keep the logic concise.

By mastering the use offorThe advanced usage of loops, combined with the various data list tags built into AnQiCMS, allows you to efficiently and flexibly display various dynamic content in templates, building powerful and aesthetically pleasing websites.


Frequently Asked Questions (FAQ)

  1. InforHow to determine if the current item in a loop is the first or last item in a list?You can useforloopUsing the built-in variables provided by the object.forloop.Counter == 1You can determine if it is the first item,forloop.Revcounter == 0(or determine)forloop.LastAlthough it is not explicitly mentioned in the document, it can be judged whether it is the last item if similar engines have{% if forloop.Counter == 1 %}这是列表的第一项{% endif %}.

  2. How can IforDisplay images in a loop and ensure they are the correct thumbnails?Most list tags of AnQiCMS, such asarchiveList/categoryList) returned byitemObjects usually containThumb(thumbnail) orLogo(Cover image) and fields. You can directly use the values of these fields as<img>Tag

Related articles

How to dynamically control the display of content in the template based on conditional logic (if/else)

In AnQiCMS template design, it is possible to flexibly control the display of content based on different conditions, which is the key to achieving website personalization and dynamic display.Whether it is to decide whether to display the picture according to whether the article has a thumbnail, or to display specific content based on the user's role, conditional logic can provide strong support.AnQiCMS uses a syntax similar to the Django template engine, which makes it very easy for webmasters familiar with web development to get started quickly.### Master the basic conditional logic in AnQiCMS templates AnQiCMS

2025-11-08

How to display copyright information and link to the record number at the bottom of the website?

Clearly display copyright information and filing number at the bottom of your website, which is not only a legal requirement but also a key factor in enhancing the professionalism and user trust of the website.AnQi CMS as an efficient content management system, fully considers these details, allowing you to easily manage and present these important site information. ### Understanding the Importance of Copyright Information and Filing Numbers The copyright statement at the bottom of the website, like a brand watermark, clearly identifies the ownership of the content to visitors, effectively protecting your original achievements.As for websites operating in mainland China

2025-11-08

How to retrieve and display the Logo, thumbnail, and slideshow group on a single page?

In Anqi CMS, single pages (such as "About Us", "Contact Us", etc.) can not only carry rich text information but also greatly enhance the attractiveness and professionalism of the page through visual elements.Retrieve and display the Logo, thumbnail, and slideshow group on a single page, which is a key step to optimize the page display effect.AnQi CMS provides flexible template tags, allowing you to easily achieve these functions.### Understand the composition of visual elements on a single page In Anqi CMS, each single page can have exclusive visual elements to meet different display needs

2025-11-08

How to obtain and display the links and titles of the previous and next articles?

When we manage and publish content in Anqi CMS, in order to enhance the user experience and content discoverability of the website, it is usually necessary to provide the function of navigating to the 'previous article' and 'next article' on the article detail page.This not only encourages readers to continue browsing the content within the site, but also provides a good internal link structure for search engine optimization (SEO).The Anqi CMS provides a very concise and intuitive template tag, allowing us to easily meet this requirement.### Core Functionality: `prevArchive` and `nextArchive`

2025-11-08

How to process and display variable content through filters (such as `truncatechars`, `safe`)?

## Optimize Content Display: Application of Variable Filters in AnQi CMS How to present information accurately and beautifully in website content management is the key to improving user experience.AnQi CMS is a flexible and efficient content management system that provides a powerful template engine, allowing us to refine and display variable content through various filters, thereby better meeting the needs of page layout and information delivery.These filters are like the 'makeup artists' of content, allowing the original data to be displayed in the most appropriate form.The AnQi CMS template engine uses syntax similar to Django

2025-11-08

How to define temporary variables or use macro functions to organize complex display logic in templates?

When using Anqicms to manage website content, we often encounter scenarios where we need to display complex data or reuse similar layouts.If the display logic in the template is not organized effectively, it will soon become long and difficult to read, and it will also be particularly difficult to maintain.Luckyly, Anqi CMS's template engine (which supports Django template engine syntax) provides powerful tools such as defining temporary variables and using macro functions, which can help us elegantly solve these problems, making the template code clear and efficient.Why do we need more flexible template logic

2025-11-08

How does AnQiCMS generate structured data through Json-LD tags to optimize the display results of search engines?

In today's highly competitive online environment, it is more important than ever to make your website content stand out in search engines.Relying solely on keyword stuffing and traditional SEO methods is no longer enough to achieve **results.Structured data, especially structured data implemented through Json-LD format, is becoming a key factor in improving search engine display results and attracting more target users' attention.AnQiCMS (AnQiCMS) knows this and provides powerful and flexible features to help you easily master this technology.### Structured Data

2025-11-08

How to efficiently display multi-site content in Anqi CMS?

In today's complex digital environment, many enterprises and content creators no longer satisfy with single-site operations.Brand expansion, regional coverage, and product line segmentation often require multiple independent websites to carry different content and marketing strategies.How can one maintain the independence of content across various sites while also efficiently managing and displaying it uniformly, which is a challenge faced by many operators.AnQi CMS, with its specially designed ability for multi-site management, provides us with an elegant solution.###

2025-11-08