How to judge whether the current item is the first or last item in the `for` loop in AnQiCMS template?

Calendar 👁️ 70

In AnQiCMS template development, we often encounter situations where we need to display data in a list loop, such as article lists, product categories, navigation menus, etc.In these loops, sometimes we need to handle the first or last item of the list specially, such as adding unique CSS styles, displaying different content, or cleverly handling the separators between list items.AnQiCMS uses a syntax similar to Django's template engine, providing us with a very intuitive and powerful tool to solve these common template logic problems.

Core mechanism:forloopobject

at AnQiCMS'sforDuring the loop, the system will automatically generate a specialforloopobject. thisforloopobject that contains detailed information about the current loop state, among which the most commonly used and crucial property for determining the start and end items isforloop.Counterandforloop.Revcounter.

  • forloop.CounterThis property indicates the current iteration of the loop, its count starts from1. If you need an index starting from 0, you can adjust it yourself.
  • forloop.RevcounterThis property indicates how many items are left from the current item to the end of the loop.In other words, it counts the number of the current item and all subsequent items.For example, if a list has a total of 5 items, the first item isRevcounterIs 5, the second item is 4, and so on, the last item isRevcounteris1.

After understanding these two properties, it becomes very simple to judge the first and last items in the loop.

Judge the first item

To determine if the current item being traversed is the first item in the loop, we just need to checkforloop.Counterwhether it is equal to1. This is a very direct and efficient method.

For example, we might want to add a special background color to the first item in the list:

{% archiveList articles with type="list" limit="5" %}
    {% for item in articles %}
        {% if forloop.Counter == 1 %}
            <div class="article-card first-highlight">
        {% else %}
            <div class="article-card">
        {% endif %}
                <h4><a href="{{ item.Link }}">{{ item.Title }}</a></h4>
                <p>{{ item.Description|truncatechars:100 }}</p>
            </div>
    {% empty %}
        <p>暂时没有文章可供显示。</p>
    {% endfor %}
{% endarchiveList %}

In this example, when the loop reaches the first article, it will receive an additionalfirst-highlightThis CSS class, convenient for us to differentiate styles, thereby highlighting the first item in the list visually.

Determine the last item

Determine if the current item is the last one in the loop, we can useforloop.Revcounterproperty. As explained before, whenforloop.Revcounterthe value is equal to1It means that we are dealing with the last item in the list.

This is particularly useful when handling separators between list items. We often want there to be a separator after each item except the last one:

{% categoryList categories with moduleId="1" parentId="0" %}
    <nav class="category-nav">
        {% for category in categories %}
            <a href="{{ category.Link }}">{{ category.Title }}</a>
            {% if forloop.Revcounter != 1 %}
                <span class="category-separator"> / </span>
            {% endif %}
        {% endfor %}
    </nav>
{% empty %}
    <p>没有找到任何分类。</p>
{% endcategoryList %}

This example demonstrates a common scenario: adding separators between navigation links. By judgingforloop.Revcounter != 1We ensure that the separator is only displayed when it is not the last item, avoiding unnecessary separators after the last category, making the page layout more tidy.

Comprehensive example

In order to better understand the practical application of these two properties, let's look at an example that combines head and tail item judgments and also showsforloopother some convenient information:

`twig

{% archiveList latestArchives with type="list" limit="6" order="CreatedTime desc" %}
    {% for article in latestArchives %}
        <div class="list-item
            {% if forloop.Counter == 1 %} is-first {% endif %}
            {% if forloop.Revcounter == 1 %} is-last {% endif %}"
        >
            <h3 class="item-title">
                <a href="{{ article.Link }}">{{ article.Title }}</a>
            </h3>
            <p class="item-meta">
                发布于:{{ stampToDate(article.CreatedTime, "2006-01-02

Related articles

How to check if the article content in the AnQiCMS template contains specific keywords and display conditions based on this?

In website content operation, we often need to flexibly adjust the display of the page according to the actual content of the article.For example, if an article mentions a specific product or event, we may want to highlight related purchase links or promotional information on the page;If the content of the article involves sensitive topics, it may be necessary to add additional disclaimers.This requirement for conditional display based on article content can be fully realized in the AnQiCMS template.AnQi CMS uses a template engine syntax similar to Django

2025-11-09

How to control the automatic escaping of HTML tags with the `autoescape` tag in AnQiCMS templates?

In the AnQiCMS template system, our daily content display core is inseparable from the handling of HTML tags.To ensure the security of the website, AnQiCMS defaults to automatically escaping variables output in templates.This mechanism effectively prevents the injection of malicious code, such as common cross-site scripting attacks (XSS).However, in some scenarios, we may need to display rich text content that includes HTML tags, at this point we need to understand how to flexibly control this automatic escaping function.### Automatically Escaped

2025-11-09

How can AnQiCMS templates safely display user-submitted rich text content to prevent potential XSS attacks?

During website operations, displaying rich text content submitted by users, such as article comments, forum posts, or blog content, is an unavoidable requirement.However, there may be malicious scripts hidden in these contents, and if they are displayed without precautions, it may lead to cross-site scripting (XSS) attacks, posing potential threats to website visitors.AnQiCMS (AnQiCMS) has fully considered this security risk in its design and provides a series of mechanisms through its template engine to help us safely handle this type of rich text content.

2025-11-09

What are the respective application scenarios of the `striptags` and `removetags` filters when cleaning HTML code in AnQiCMS templates?

In AnQiCMS template design, we often encounter situations where we need to clean up or simplify the HTML code in the content.This is not just for beauty, but also to ensure the correct display of content, improve page loading efficiency, and even prevent potential security risks.The Aqie CMS provides two very practical filters: `striptags` and `removetags`.Although they are all related to the removal of HTML tags, each has a clear application scenario.### `striptags`

2025-11-09

How to implement the `cycle` tag to alternate the display of different styles or data in AnQiCMS templates?

AnQiCMS provides many practical tags for template development, making content display more flexible and efficient.Among them, the `cycle` tag is such a clever tool that it can help us achieve the alternation of data or styles in loops, making the page content more dynamic and visually attractive. ### Understanding the `cycle` tag: Sequence controller in loops In web design, we often encounter situations where we need to apply different styles to repeating elements or display different types of data in a specific order. For example

2025-11-09

How to skip certain items in the `for` loop of the AnQiCMS template based on specific conditions?

In AnQiCMS template development, we often need to display a series of contents, such as article lists, product lists, or navigation menus.But often, we do not want to display all the data at once, but rather hope to skip a part of it according to certain specific conditions, making the final content displayed more accurate and in line with the user's needs.AnQiCMS uses a syntax similar to the Django template engine, which provides a powerful and flexible tool for us to implement this conditional skipping.To implement `for`

2025-11-09

How to judge whether a custom field exists in the AnQiCMS template and conditionally render according to its value?

In AnQiCMS template development, flexibly displaying content is the key to improving user experience and website professionalism.Among them, judging custom fields and rendering conditions based on their values is an indispensable skill to achieve this goal.In this way, you can ensure the precise display of page content, avoid displaying empty values, or dynamically adjust the page layout and functionality based on specific data.### Understanding AnQiCMS Custom Fields and Their Retrieval Methods in Templates AnQiCMS is a powerful content management system

2025-11-09

How to determine if the `Content` field of the document is empty using the `archiveDetail` tag and display alternative content?

How can you elegantly handle the case where the document content is empty in AnQi CMS?During the operation of the website, we often publish various types of documents, which contain important information.However, sometimes for various reasons, such as the content is still in draft stage, data is missing during import, or simply some documents are only titled without detailed text, we may encounter the situation where the `Content` field of the document is empty.If the template does not perform any processing when rendering these document detail pages, the user may see a blank page area, which not only affects user experience

2025-11-09