How to iterate over an array or object list in AnQiCMS template and display loop count and remaining quantity?

Calendar 👁️ 65

In website content management, dynamically displaying list data is a basic yet crucial function.Whether it is an article list, product display, or user comments, we need to present data to users efficiently.How to clearly indicate the order of list items or inform the user how much content has not been viewed can greatly enhance the user experience and readability of the content.AnQiCMS (AnQiCMS) with its flexible template engine can help us easily meet these needs.

The AnQiCMS template system uses syntax similar to Django, which allows content operators to quickly get started even without a strong programming background.When dealing with the iteration of arrays or lists of objects, the built-in loop variables in the template provide us with great convenience, especially in terms of easily obtaining the loop count and remaining number.

Flexible applicationforLoop through data

In the AnQiCMS template, we mainly use{% for ... in ... %}tags to traverse array or object lists. For example, to display an article list, we can construct the basic loop like this:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <li><a href="{{item.Link}}">{{item.Title}}</a></li>
    {% empty %}
        <li>目前还没有内容发布。</li>
    {% endfor %}
{% endarchiveList %}

This code will retrieve the most recently published 10 articles and display their titles and links one by one. If the list is empty,{% empty %}a friendly prompt will be displayed.

Get loop count:forloop.Counter

To make the list more organized, we often need to add a serial number to each list item. In AnQiCMS'sforthe loop,forloop.CounterThis variable can be put to good use. It will return the current loop count and it is from1and counting.

For example, we want to add a serial number to each article:

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
        <li>
            <span>{{ forloop.Counter }}.</span>
            <a href="{{item.Link}}">{{item.Title}}</a>
        </li>
    {% empty %}
        <li>目前还没有内容发布。</li>
    {% endfor %}
{% endarchiveList %}

Such, each article will display a serial number starting from 1, making it clear for the user to see the total number of the list and the current browsing position.This is particularly important for information that needs to be presented in order (such as step guides, leaderboards, etc.)

Master the remaining quantity:forloop.Revcounter

In addition to the positive counting, sometimes we also need to know how much content is left after the current list item.forloop.RevcounterVariables are designed for this. It returns the number of remaining elements after the current loop item (including the current item, that is, the total number minus the current loop count plus 1).

For example, when displaying a list of time-limited promotional products, we may want to emphasize that there are still X items left:

{% archiveList products with type="list" moduleId="2" limit="5" %}
    {% for item in products %}
        <li>
            <a href="{{item.Link}}">{{item.Title}}</a>
            {% if forloop.Revcounter > 1 %}
                <span> (还剩 {{ forloop.Revcounter - 1 }} 件)</span>
            {% else %}
                <span> (这是最后一件了!)</span>
            {% endif %}
        </li>
    {% empty %}
        <li>目前没有优惠商品。</li>
    {% endfor %}
{% endarchiveList %}

Please note,forloop.RevcounterIt is countingFrom the current item to the last oneThe number. Therefore, if we want to express how many items are left after the current item, we need to subtractforloop.Revcounter1. Whenforloop.RevcounterWhen equal to 1, it means that the current item is the last item in the list.

Integrated application, optimizing user experience

toforloop.Counterandforloop.RevcounterUsing them together, we can create a list with more interactivity and information. For example, on a product list page, we might need:

  1. To add a serial number to each product.
  2. Handle special styles for the first and last products.
  3. Display 'Current X of Y' or 'Remaining Z' in the list.

This is a more complete example that shows the power of these variables:

<ul class="product-list">
    {% archiveList products with type="list" moduleId="2" limit="8" %}
        {% for product in products %}
            <li class="product-item {% if forloop.Counter == 1 %}first-item{% endif %} {% if forloop.Revcounter == 1 %}last-item{% endif %}">
                <a href="{{product.Link}}" title="{{product.Title}}">
                    {% if product.Thumb %}
                        <img src="{{product.Thumb}}" alt="{{product.Title}}" class="product-thumb">
                    {% else %}
                        <img src="/static/images/placeholder.png" alt="无图片" class="product-thumb">
                    {% endif %}
                    <h3 class="product-title">{{ forloop.Counter }}. {{product.Title}}</h3>
                </a>
                <p class="product-meta">
                    <span>浏览量: {{product.Views}}</span>
                    {% if forloop.Revcounter > 1 %}
                        <span class="remaining-items"> (之后还有 {{ forloop.Revcounter - 1 }} 个商品)</span>
                    {% else %}
                        <span class="remaining-items"> (已是最后一个)</span>
                    {% endif %}
                </p>
                {% if product.Description %}
                    <p class="product-description">{{ product.Description|truncatechars:80 }}</p>
                {% endif %}
            </li>
        {% empty %}
            <li class="no-products-found">抱歉,目前没有找到任何产品。</li>
        {% endfor %}
    {% endarchiveList %}
</ul>

In this example, we not only achieveforloop.Counternumber display, but also make use of it andforloop.RevcounterAdd a special CSS class to the first and last elements of the list (first-itemandlast-itemThis provides great style control flexibility for front-end designers. At the same time, we also friendly prompt the user how many products are left after the current product.

By these built-in loop variables, AnQiCMS makes the dynamic display of template content more refined and user-friendly.Apply them flexibly; it will help you build a more attractive and practical website.


Frequently Asked Questions (FAQ)

Q1:forloop.Counterandforloop.RevcounterWhat is the difference?

A1:forloop.CounterRepresents the forward count of the current loop item, starting from1and increasing until the end of the list. For example, in a list with 5 elements,forloop.Counterthey will be in order.1, 2, 3, 4, 5Howeverforloop.RevcounterIt represents the total number of items from the current loop item to the end of the list. In the same 5-element list,forloop.Revcounterthey will be in order.5, 4, 3, 2, 1In simple terms,Countertells you “which item this is,”Revcountertells you “how many items are left (including the current item).

Q2: How do I determine if the current element in the loop is the first or last in the list?

A2: To check if it is the first element,forloop.Counter == 1If the condition is met, it means it is the first item in the list. To determine if it is the last element, you can checkforloop.Revcounter == 1. When this condition is met, it indicates that the current element is the last item in the list. You can use these conditions to apply specific styles or display different content.

Q3: How do I display a custom prompt if the array or object list I loop through is empty, instead of nothing?

A3: AnQiCMS'forThe loop tag built-in included a{% empty %}sub-tag, specifically used for handling this situation. When the list you loop through is empty,{% empty %}and{% endfor %}the content between them will be displayed. For example:

{% for item in my_list %}
    {# 显示列表项内容 #}
{% empty %}
    <p>抱歉,这里还没有内容。</p>
{% endfor %}

Related articles

How to display or hide content blocks in AnQiCMS templates based on conditions (such as `if` statements)?

In website content operation, we often need to display or hide specific content based on different situations, such as displaying special event information on holidays or showing different operation buttons based on the user's status.AnQiCMS provides a flexible template engine, allowing you to easily implement these dynamic content controls, with the most core tool being the conditional statement - `if`. AnQiCMS template syntax is similar to the popular Django template engine, and it is very easy to get started with.

2025-11-07

How to get and display detailed information of a specific user, such as username, avatar, and level in AnQiCMS template?

In website operation, displaying personalized information to users, such as usernames, avatars, and membership levels, can greatly enhance user experience and website interaction.AnQiCMS as a flexible content management system provides intuitive template tags to help us easily achieve this goal.The AnQiCMS template system has adopted a syntax similar to Django templates, allowing backend data to be called through concise tags.When we want to display detailed information about a specific user

2025-11-07

How to loop to display user group information in AnQiCMS template?

In the website built with AnQiCMS, the user grouping function provides us with powerful content management and user permission division capabilities, whether it is to implement membership content, display different information according to user level, or plan VIP services, user grouping is an indispensable foundation.How to flexibly display these user grouping information on the front-end template of a website, which is a focus for many operators.AnQiCMS uses a template engine syntax similar to Django, which makes template writing intuitive and efficient.When it comes to user group information, the system provides

2025-11-07

How to customize the display content and link of the homepage Banner in AnQiCMS template?

In website operation, the homepage banner acts as the 'facade' of the website, and its visual effect and guiding role are crucial.A well-designed and tasteful Banner can not only attract visitors' attention but also effectively convey the core information of the website and guide users to take the next step.For friends using AnQiCMS, how to flexibly customize the display content and link of the home page Banner is a key step to improve the user experience and marketing effect of the website.

2025-11-07

How to define and use temporary variables in AnQiCMS templates to simplify complex data processing?

In AnQiCMS template development, we often encounter situations where we need to process or reuse complex data.Writing complex logic or data paths repeatedly in templates not only makes the code long and hard to read, but also affects maintenance efficiency.At this time, skillfully using temporary variables can make template code clearer and more concise, as well as more flexible in data processing.AnQiCMS's template engine provides a powerful and flexible variable definition mechanism that can help us effectively manage and process page data.

2025-11-07

How does AnQiCMS template reference other template files (such as `header.html`, `footer.html`) to achieve code reuse?

In website construction and maintenance, how to efficiently manage code and avoid redundant labor is the key to improving development efficiency and ensuring website consistency.For users who build websites using AnQiCMS, its flexible template engine provides a powerful code reuse mechanism, allowing us to easily refer to other template files, such as the common header (header) and footer (footer), thereby achieving modular development.The template design of AnQiCMS borrows the syntax features of the Django template engine

2025-11-07

How to display Markdown formatted article content in AnQiCMS template and render it correctly to HTML?

In a content management system, Markdown has become the preferred writing format for many content creators, it is concise, efficient, and easy to convert to structured HTML.For AnQiCMS users, using Markdown to write articles can not only improve writing efficiency but also better organize content structure.Luckyly, AnQiCMS deeply supports Markdown formatted article content and provides a perfect mechanism to ensure that they are correctly rendered into beautiful HTML pages on the website front-end.### Start

2025-11-07

How to implement the parameter filtering function of the article list in AnQiCMS (such as filtering by custom properties)?

As the content of the website becomes richer, users often hope to find the information they are interested in more accurately, rather than searching for a needle in a haystack of disordered content.For operators, providing flexible article list filtering functions can not only significantly improve user experience but also effectively help users discover more related content, thereby increasing the time spent on the website and interaction.AnQiCMS fully understands this need, through its highly flexible content model and powerful template tag system, making it extremely simple and intuitive to implement the parameter filtering function for the article list.Even if it is a custom attribute

2025-11-07