How to get the total length of the document list `archives` being traversed in the `for` loop?

Calendar 👁️ 70

In AnQiCMS template development, we often need to iterate over document lists, such as througharchiveListtag to get the content. In such aforIn a loop, knowing the total length of the current list is a very practical need, as it can help us implement some specific display logic, such as showing 'Article N of M' or determining if the list is empty.

The AnQi CMS template engine borrows the syntax of Django, providing a set of intuitive and powerful tags and filters to process data. To getforLooparchivesThe total length of the document list, we can take advantage of the filter functions provided by the template engine.

Core concept: List data and filters

Through the AnQiCMS template,archiveListget tags fromarchivesIt is usually an array (or a slice in Go language) object. The template engine provides a name for this type of array object calledlengthThe filter, which can directly calculate the number of elements it contains.

lengthThe principle of the filter's operation is very simple: it receives a string, an array, or a key-value pair and returns the number of elements it contains.For an array or list, it returns the total number of elements.

How to obtainarchivestotal length

The most direct and recommended way is toforbefore the loop starts, uselengththe filter to calculatearchivesThe total length of the list, and store it in a new variable.

  1. UsearchiveListGet the document list:First, you need to usearchiveListTag to get your document list. For example, we get a list containing 10 articles:

    {% archiveList archives with type="list" limit="10" %}
        {# 接下来我们会在这个区域处理 archives 列表 #}
    {% endarchiveList %}
    
  2. Get the total length outside the loop and assign it to a variable:InforLoop througharchivesBefore that, we can directly apply toarchivesthis variable.lengthFilter. We usually combine it withsetlabel to assign it to a new variable, such astotal_count.

    {% archiveList archives with type="list" limit="10" %}
        {% set total_count = archives|length %} {# 使用 length 过滤器获取总长度并赋值给 total_count #}
        {# ... 后续的 for 循环和展示逻辑 ... #}
    {% endarchiveList %}
    

    Herearchives|lengthand calculatearchivesThe actual number of documents in the list.

  3. InforUsing the total length in the loop:Obtained the total lengthtotal_countAfter that, you can use it inforThe loop internally. For example, combineforloop.Counter(The current loop index, starting from 1) to display the position of the current document in the total list:

    {% archiveList archives with type="list" limit="10" %}
        {% set total_count = archives|length %}
        <p>本批次文章共 <strong>{{ total_count }}</strong> 篇。</p>
        <ul>
            {% for item in archives %}
                <li>
                    <a href="{{ item.Link }}">{{ item.Title }}</a>
                    <span> (第 {{ forloop.Counter }} 篇 / 共 {{ total_count }} 篇)</span>
                </li>
            {% empty %}
                <li>当前分类或条件下暂无文章。</li>
            {% endfor %}
        </ul>
    {% endarchiveList %}
    

Complete example code

This is a complete example that combines obtaining a document list, calculating the total length, and using it in a loop:

{# 假设这是一个文章列表页,我们想展示该分类下的文章及其总数 #}

{% archiveList articles with type="list" categoryId="1" limit="20" %} {# 获取 ID 为 1 的分类下最多 20 篇文章 #}
    {% set total_articles_count = articles|length %} {# 计算文章列表的总长度 #}

    {% if total_articles_count > 0 %} {# 判断列表是否为空 #}
        <h2>最新文章 (共 {{ total_articles_count }} 篇)</h2>
        <div class="article-list">
            {% for article in articles %}
                <div class="article-item">
                    <h3><a href="{{ article.Link }}">{{ article.Title }}</a></h3>
                    <p class="meta">
                        发布时间:{{ stampToDate(article.CreatedTime, "2006-01-02") }}
                        浏览量:{{ article.Views }}
                        (第 {{ forloop.Counter }} 篇)
                    </p>
                    <p>{{ article.Description }}</p>
                    {% if article.Thumb %}
                        <img src="{{ article.Thumb }}" alt="{{ article.Title }}" class="article-thumb">
                    {% endif %}
                </div>
            {% endfor %}
        </div>
    {% else %}
        <p>抱歉,当前分类下没有找到任何文章。</p>
    {% endif %}
{% endarchiveList %}

In this way, you can easily use it in the Anqi CMS template.forRetrieve the total length of the document list in a loop and flexibly display and handle the logic according to actual needs.This approach conforms to the design philosophy of the template engine and ensures the clarity and maintainability of the code.


Frequently Asked Questions (FAQ)

Q1: IfarchivesThe list is empty,archives|lengthwhat will be returned?A1: IfarchivesThe list is empty,archives|lengthit will return0. You can use this feature, combined withif statements (such as those in the example){% if total_articles_count > 0 %}To determine whether the list has content, so as to display different prompt information, such as 'No content'.

Q2:forloop.Counterandarchives|lengthWhat is the difference?A2:forloop.CounterIs inforA special variable used inside the loop, it representscurrentThe number of iterations, starting from1starts increasing. Whilearchives|lengthis obtained by applying to the entirearchiveslistlengthfilter obtainedTotalThe number of elements, it remains unchanged throughout the loop cycle. In simple terms,forloop.Counteris the current position,archives|lengthis the total length.

Q3: BesidesarchivesI can uselengthDoes the filter get the length of other variables?A3: Yes,lengthThe filter is not only applicable to passing througharchiveListobtainedarchivesA list, it can also be used for any array (slice), string, or key-value pair (map) type of variable. For example, you can use{{ "Hello World"|length }}to get the length of a string, or use{{ my_custom_array|length }}Get the length of a custom array.

Related articles

How to judge if the length of the user comment content `comment.Content` exceeds the limit for front-end verification?

In website operation, the comment feature is an important part of user interaction.To maintain a good community environment and data quality, we usually limit the length of the comments submitted by users.Front-end validation plays a crucial role in this process, providing immediate feedback before submission to avoid failure due to content length, thereby enhancing user experience and reducing server load.How can we judge whether the length of the user comment content `comment.Content` exceeds the limit in the website built using AnQiCMS?

2025-11-08

How to get the number of top-level menu items in the website navigation list `navList`?

In website content operation, the navigation menu is the first door for users to interact with the website content.AnQiCMS (AnQiCMS) provides a flexible `navList` tag to help us easily manage and display website navigation.Sometimes, in order to achieve a specific layout, style, or dynamic adjustment, we need to know the specific number of top-level navigation menu items on the website.This article will thoroughly introduce how to obtain the number of top-level menu items in the `navList` navigation list of AnQiCMS templates.### Understand `navList`

2025-11-08

How to check how many images are included in the group image `archive.Images` array on the article detail page?

It is crucial to manage the image display on the article detail page flexibly and accurately when building website content in AnQi CMS.Especially when we need to use multiple images to enrich the content of an article, the collage feature (usually corresponding to the `archive.Images` field) provides an efficient and convenient solution.In the operation, sometimes we need to understand how many images a specific article detail page contains, whether it is for page layout design, content statistics, or executing logic judgments under specific conditions.This article will elaborate on how to accurately check in AnQi CMS templates

2025-11-08

How to limit the maximum number of characters that `archive.Content` displays in the summary in the template?

In website operation, how to efficiently display content summaries that can attract visitors to click and maintain the page tidy is a common and important issue.For those who use AnQiCMS, we often need to extract the essence of the document content as a summary to be displayed on list pages, search result pages, or related article recommendation modules.This article will introduce how to precisely control the maximum number of characters displayed in the `archive.Content` field in the AnQiCMS template summary.### Understand `archive.Content`

2025-11-08

How to dynamically display the character length of the website name `SiteName`, such as for SEO title preview?

In content operation and website SEO optimization, the title plays a crucial role.A well-constructed SEO title can not only attract the attention of users, but also effectively improve the visibility of the page in the search engine results page (SERP).Among them, the character length of the title is a detail that should not be ignored.Title length can cause it to be truncated, affecting information delivery; too short may not fully utilize the display space, missing the opportunity to attract users.AnQiCMS (AnQiCMS) is a powerful content management system that provides a rich set of tools for SEO optimization

2025-11-08

How to determine if the `linkList` friendship link list returns an empty result and decide whether to display the friendship link block?

In website operation, friendship links are an important part of enhancing website authority and promoting SEO, and can also provide users with more valuable external resources.However, during the process of website construction, friendship links are not always full.If the friend link list is empty but still displays an empty link area on the page, it will undoubtedly affect the overall aesthetics and professionalism of the website.AnQiCMS provides flexible template tags, allowing us to intelligently judge whether the friend link list is empty and decide whether to display the corresponding block according to the actual situation. Next

2025-11-08

How to get the total number of categories returned by `categoryList` to control the page layout or display the 'All' option?

In Anqi CMS template development, the `categoryList` tag is one of the core tools for website content organization and navigation construction.It can help us easily display the classification structure of articles, products, and other content.However, in practical applications, we may not only need to display the categories themselves, but also need to flexibly adjust the page layout based on the number of categories, or decide whether to display an 'All' option so that users can browse the content under all categories.How do we use `categoryList`

2025-11-08

How does AnQiCMS manage the display of content for different brands or sub-sites uniformly?

In today's complex network environment, many enterprises or individuals need to manage multiple brand sites, product line special theme sites, or regional sub-sites.How to efficiently and uniformly manage the massive content of these sites to ensure that each site has a unique brand image and content display, which has become a major challenge for operators.AnQiCMS is a powerful content management system dedicated to solving this problem, it makes it easy and convenient to manage the unified content display of multiple brands or sub-sites through its unique design concept and rich features.### Unified Management

2025-11-08