How to get the index starting from 1 in the current iteration of the `for` loop?

Calendar 👁️ 53

Use AnQiCMS template easily to get the 'first' and 'Nth' indices in the loop

In website content operation, we often need to display a series of contents on the page, such as article lists, product displays, navigation menus, etc.In order to better present this content, we often need to finely control each item in the list, such as adding special styles to the first item, or displaying the item's number in the list.For friends using AnQiCMS, understanding how to use templates inforLooping to get the current iteration item index is a very practical skill that can greatly enhance the flexibility of the template.

AnQiCMS uses a template engine syntax similar to Django, which makes it very convenient for content developers to build dynamic pages. When dealing with list data, we usually useforThe loop tag is used to iterate over a data collection. To get the index of each element in the loop, AnQiCMS provides a built-in special variable to make this requirement easy.

Get to knowforloop.CounterYour 1-based loop counter:

When you use in AnQiCMS template:{% for item in collection %}such a structure to iterate over a list (such as an article collection, category list, or image group) when the template engine quietly provides a special variable namedforloopthis special variable.forloopThe variable contains a lot of useful information related to the current loop state, and the most core of which is today's main character -forloop.Counter.

forloop.CounterAs the name implies, it is a counter. Its uniqueness lies in the fact that it starts counting from1This means that when the loop runs for the first time,forloop.CounterThe value is 1; the second is 2, and so on until the loop ends. This is very convenient for scenarios where you need to number list items starting from 1.

Let's look at a simple example, suppose we are displaying a product list and we want to show the serial number for each product:

{% archiveList products with type="list" limit="5" %}
    {% for product in products %}
    <div class="product-item">
        <span class="product-number">{{ forloop.Counter }}.</span>
        <h3><a href="{{ product.Link }}">{{ product.Title }}</a></h3>
        <p>{{ product.Description }}</p>
    </div>
    {% endfor %}
{% endarchiveList %}

In this code block,{{ forloop.Counter }}Will display "1." for the first product in the list, "2." for the second product, and so on.This intuitive 1-based counting method perfectly fits human reading habits and many business logic needs.

Masterforloop.Revcounter: Counting backwards from the 'tail' index

In addition to the positive counting, AnQiCMS also provides us withforloop.Revcounterthis variable. Andforloop.CounterOn the contrary,forloop.Revcounterwhat it provides isa reverse count, starting from 1 as wellthe index. This means that the last item in the list, itsforloop.Revcountervalue is 1; the second-to-last is 2, and so on until the first item in the list, itsforloop.Revcountervalue equals the total length of the list.

forloop.RevcounterIt can be very effective in certain specific scenarios, such as when you need to handle the last few items in the list specially, or display the sequence numbers in reverse order.

Combine these two counters to build more complex logic:

{% categoryList categories with moduleId="1" parentId="0" %}
    {% for category in categories %}
    <li class="category-item {% if forloop.Counter == 1 %}first{% endif %} {% if forloop.Revcounter == 1 %}last{% endif %}">
        <span class="index">{{ forloop.Counter }}</span>. 
        <a href="{{ category.Link }}">{{ category.Title }}</a>
        <span class="remaining-items">(还有{{ forloop.Revcounter - 1 }}个)</span>
    </li>
    {% empty %}
    <li>暂无分类。</li>
    {% endfor %}
{% endcategoryList %}

In this example, we not only added positive numbering to each category but also utilizedforloop.Counter == 1Added to the first elementfirstClass, utilizingforloop.Revcounter == 1Added to the last elementlastClass. At the same time,forloop.Revcounter - 1Then cleverly displays how many elements are behind the current item.

Practical scenarios and techniques

forloop.Counterandforloop.RevcounterThese variables are very useful in actual development:

  1. Number display: The most common use is to add numbers to list items, such as “1. Title A”, “2. Title B”, and so on.
  2. condition style: you can according toforloop.Counterorforloop.RevcounterThe value to add different CSS classes to elements at specific positions, such as the first, last, or every N elements to add special styles. This istag-/anqiapi-other/3498.htmlandtag-/anqiapi-archive/141.htmlFor example, it is also reflected in the example{% if forloop.Counter == 1 %}active{% endif %}.
  3. Unique ID generation: Combined with other variables, it can generate a unique ID on the page, convenient for JavaScript operations or anchor links.
  4. Loop exit/limit: Althoughforloop.CounterIt does not directly control the loop, but you can combineifstatements, to perform special processing or interrupt the logic when a certain count is reached.
  5. Handling empty data: It is worth mentioning that AnQiCMS'sforLoops also support{% empty %}tag, when the collection being traversed is empty, it will executeemptythe content in the block, at this timeforloopthe variable naturally does not exist.

By flexible applicationforloop.Counterandforloop.Revcounter,AnQiCMS content operators and template developers can easily implement various complex list displays and interactive logic, making the website content more vivid and organized.


Frequently Asked Questions (FAQ)

Q1: AnQiCMS'forthe loop,forloop.CounterIs the provided index starting from 0 or 1?

A1: AnQiCMS'forloop.Counterwhat it provides isCounting starts from 1index. This means that the first element of the list isforloop.CounterThe value is 1, the second is 2, and so on. If you need a 0-based index, you can simply use{{ forloop.Counter - 1 }}to achieve.

Q2: Can I get the reverse index of the list item besides the positive index?

A2: Of course you can. AnQiCMS also providesforin the loop.forloop.RevcounterA variable that can provide you with the reverse index of the current iteration item in the list, which also starts from 1. For example, the last element in the list isforloop.Revcounterthe value is 1, the second last is 2.

Q3: How do I apply special styles to the first or last item in a list?

A3: You can useforloop.Counterandforloop.RevcounterCombineifConditional judgment can be implemented. For example, to add style to the first item, you can use{% if forloop.Counter == 1 %}; To add style to the last item, you can use{% if forloop.Revcounter == 1 %}This can very accurately control the performance of specific position elements.

Related articles

How to use the `{% for ... in ... %}` tag in AnQiCMS templates to iterate over a data list?

How to flexibly use `{% for ...` in Anqi CMS templatein ...How to iterate over a data list with `%}` tag?As an experienced website operations expert, I fully understand the importance of an efficient and flexible template system for content management.AnQiCMS, as an enterprise-level content management system based on the Go language, draws on the essence of the Django template engine in template design, especially its powerful data traversal capabilities, particularly `{% for ...in ...The `tag is one of the core tools for building dynamic page content.

2025-11-06

How to get the accurate length of strings, arrays, or key-value pairs in AnQi CMS templates?

In website content management, we often need to finely control the displayed data, such as limiting the number of characters in article titles, checking if the image collection is empty, or counting how many entries are in a list.As an experienced website operations expert, I know how AnQiCMS' powerful and flexible template engine can help us meet these needs.

2025-11-06

What does the `get_digit` filter return when it encounters a non-existent position?

AnQiCMS (AnQiCMS) leverages the efficient characteristics and flexible template engine of the Go language to provide strong support for content management.During template development, we often use various filters to format and process data.Among them, the `get_digit` filter is a utility used to extract a specific digit from a number.Then, how will it respond when we use it to extract a digit from a number at a position that actually does not exist?Let's delve deeper into it.

2025-11-06

How to accurately extract a specified digit from a number in Anqi CMS template?

In the template world of AnQi CMS, efficiently and flexibly handling data is the key to website operators improving the expression of content.As an experienced website operations expert, I know the power of template language lies in its ability to transform complex technical logic into simple and practical content presentation.Today, we will focus on a seemingly simple but extremely practical need: how to accurately extract the digit you want from a number in the Anqi CMS template.

2025-11-06

How to get the remaining number of items in the current iteration of the `for` loop (reverse index)?

As an experienced website operations expert, I know that the template function of the content management system is the core of flexible and diverse content display on the website.AnQiCMS (AnQi CMS) leverages the efficient features of the Go language and the Django-like template syntax, providing us with powerful content operation support.Today, let's delve deeply into a practical skill often encountered in template development: how to elegantly obtain the remaining items of the current iteration in the `for` loop, which is what we often call the 'reverse index'.

2025-11-06

How to elegantly display a 'no content' prompt when using the `empty` tag in AnQiCMS `for` loop?

In the daily operation of the website, we understand that the way content is presented is crucial to user experience.A well-designed website that not only provides rich information but also gives users friendly prompts when content is missing, avoiding the embarrassment of blank pages or error messages.

2025-11-06

How does the `{% for ... in ... reversed %}` tag implement reverse traversal of a data list?

As an experienced website operations expert, I am well aware of the importance of content presentation for user experience and information delivery.In AnQiCMS (AnQiCMS) such an efficient and flexible content management system, mastering its powerful template tag functions is the key to our refined content operation.Today, let's delve into a seemingly simple yet extremely practical template tag modifier——`{% for ...in ...reversed %}`, see how it plays a role in the reverse traversal of the data list.

2025-11-06

How to correctly call the message form tag on the AnQiCMS website?

As an experienced website operation expert, I know the importance of the comment form in website operation.It is not only the bridge of communication between users and websites, but also the key point for us to collect user feedback, improve service quality, optimize content strategy, and even promote business growth.AnQiCMS as an efficient and customizable enterprise-level content management system provides strong and flexible support for the message function, allowing website administrators to easily build and manage various message scenarios.This article will focus on how to correctly call the comment form tag in the AnQiCMS website?This topic

2025-11-06