How to calculate the number of elements in a string (such as an article title) or an array (such as a tag list) in AnQiCMS templates?

Calendar 👁️ 64

In AnQi CMS template design, we often need to make accurate statistics of the content on the page, whether it is to dynamically display the number of data or to make conditional judgments based on the number, mastering how to calculate the number of elements in a string or array is particularly important.AnQiCMS's powerful template engine provides a concise and efficient method to handle these requirements.

Obtaining the length of a string

When we need to know the length of a string, such as the number of characters in an article title, AnQiCMS template provides|lengthFilter. This filter can help us easily obtain the character count of any string variable.

Assuming we want to display the character length of the article title on the page, we can do it like this:

<p>文章标题:{{ archive.Title }}</p>
<p>标题长度:{{ archive.Title|length }} 个字符</p>

Here, archive.TitleRepresents the article title on the current page. By adding|lengthThe template engine will calculate the total number of characters contained in the title.It should be noted that AnQiCMS calculates the length of strings based on UTF-8 encoding, which means that a Chinese character is also counted as a unit, which is very friendly for operators of multilingual websites.

Moreover, if you are more focused on counting the number of words in English titles rather than characters, AnQiCMS also provides|wordcounta filter. For example:

<p>文章标题:{{ archive.Title }}</p>
<p>标题中的单词数量:{{ archive.Title|wordcount }} 个</p>

This filter calculates the number of words in a string by using spaces as delimiters, which is very useful for summarizing statistics of English content.

Statistics of the number of elements in an array or list

For data of array or list type, such as tag lists of articles, sub-items in navigation menus, or image collections, we can also use|lengthThe filter counts the total number of elements it contains. This is very convenient for implementing some dynamic display logic, such as 'show tag cloud if there are tags' or 'show carousel if the number of images is greater than 1' and other scenarios.

For example, on a document detail page, we may need to display all the tags associated with the article and find out how many tags there are:

{% tagList tags with limit="10" %}
    {% if tags|length > 0 %}
        <p>本文共有 {{ tags|length }} 个相关标签:</p>
        <ul>
            {% for item in tags %}
                <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
            {% endfor %}
        </ul>
    {% else %}
        <p>本文暂无相关标签。</p>
    {% endif %}
{% endtagList %}

In the code above, we first usetagListLabel to get the article tag list and assign it totagsthe variable. Then, bytags|lengthCheck if the tag list is empty and display the corresponding text and list content. This method also applies to other array types of variables, such as fromarchiveDetailobtained fromImages(Image list of the article) orContentTitles(List of titles in the article content).

For example, determine if the article has images:

{% archiveDetail archiveImages with name="Images" %}
    {% if archiveImages|length > 0 %}
        <p>本文共包含 {{ archiveImages|length }} 张配图:</p>
        {% for img in archiveImages %}
            <img src="{{ img }}" alt="配图" />
        {% endfor %}
    {% else %}
        <p>本文没有配图。</p>
    {% endif %}
{% endarchiveDetail %}

Count the number of times a specific element appears in an array or string

In addition to getting the total length, sometimes we also need to know how many times a specific value appears in a string or array. AnQiCMS provides|countFilter. This filter can calculate the frequency of a specified keyword in a string or the number of times a specific element appears in an array.

For example, count the number of times a keyword appears in the article content:

{% archiveDetail articleContent with name="Content" %}
    <p>关键词“AnQiCMS”在文章中出现了 {{ articleContent|count:"AnQiCMS" }} 次。</p>
{% endarchiveDetail %}

Or, count the number of times a specific color appears in a custom color list:

{% set colors = '["red", "blue", "red", "green", "red"]'|list %}
<p>在颜色列表中,“red”出现了 {{ colors|count:"red" }} 次。</p>

Through these flexible filters, AnQiCMS makes it easy for website operators to count and dynamically display the number of contents in templates, whether it is to optimize user experience or improve the SEO performance of the website, these features provide a solid foundation.


Frequently Asked Questions (FAQ)

1.|lengthand|countWhat are the main differences of the filter? |lengthThe filter is used to get the total number of characters in a string or the total number of elements in an array/list. It counts the 'how many'.|countThe filter is used to count how many times a specific substring or element appears in a larger string or array. It counts the "frequency of a specific value".

2. In a loop(forHow to get the current element's position or how many elements are left in the loop?in AnQiCMS'sforIn a loop, you can use special loop variables to get this information.{{ forloop.Counter }}It will display the current loop index (starting from 1), while{{ forloop.Revcounter }}it will display the number of remaining elements. These variables are automatically available within the loop and do not require additional definition.

How many characters is a Chinese character counted as when calculating the length of a Chinese string?AnQiCMS's template engine calculates the length of a string based on the actual number of characters encoded in UTF-8.This means that a Chinese character, regardless of how many bytes it occupies internally, will be uniformly counted as 1 character externally.This ensures that the length calculation is consistent with the user's visual perception.

Related articles

How to convert newline characters in multi-line text to the HTML `<br>` tag for display in AnQiCMS templates?

In AnQiCMS content management, we often enter multi-line text with line breaks, such as article content, product descriptions, or contact addresses.However, when this content is displayed on the website front-end, we may find that the original clear line breaks are missing, and all the text is squeezed into a single line.This not only affects the reading experience of the content, but may also be inconsistent with our original design intention.Why is this happening?

2025-11-07

How to remove specific HTML tags from an HTML string in the AnQiCMS template (such as `<i>`, `<span>`)?

In AnQiCMS template development, we often encounter content coming from rich text editors, or imported from external sources, which may contain some HTML tags that we do not want to display at specific locations.For example, in the summary section of the article list, we may only want to display plain text, or we may need to remove specific tags such as `<i>`, `<span>`, etc. to maintain the consistency of the page style.

2025-11-07

How to truncate a long string (such as an article summary) to a specified length and display an ellipsis in the AnQiCMS template?

In website content operation, the display length of article abstracts or introductions often needs careful control.Long content can affect the layout and user experience of a page, while a concise summary with an ellipsis can effectively guide users to click and read more details.AnQiCMS provides flexible template tags and filters, allowing us to easily implement this feature.

2025-11-07

How to judge whether a variable is empty in AnQiCMS template and set a default display value?

During the development of website templates, it is often encountered that the variable value may be empty.If not properly handled, the front-end page may appear with unattractive blank areas, even displaying some default placeholders (such as `nil` or `null`), which undoubtedly affects user experience and the professionalism of the website.AnQiCMS (AnQiCMS) provides a powerful and flexible template engine that can help us elegantly determine whether variables are empty and set appropriate default display values.

2025-11-07

How to automatically convert a URL string into a clickable hyperlink and set `nofollow` in the template of AnQiCMS?

In the daily operation of AnQi CMS, we often need to display external links in the website content.These links, if they are just simple text, not only affect the user experience, but also cannot effectively convey information.At the same time, in order to follow the **practice** of search engine optimization (SEO), especially for links pointing to external sites, we usually want to add the `rel="nofollow"` attribute to avoid unnecessary "weight loss" or passing unnecessary trust.AnQi CMS provides a simple and efficient method to solve this problem.### Core Function Revelation

2025-11-07

How to format a floating-point number to a specified number of decimal places in AnQiCMS template?

In the presentation of website content, we often need to display various numbers, such as product prices, discount percentages, or statistical data.These numbers are often floating-point numbers, and in order to ensure the beauty of the page layout and the clarity of the information, we usually need to format them, such as uniformly retaining two decimal places.In the AnQiCMS template, thanks to its flexible template engine, we can conveniently use the built-in `floatformat` filter to meet this requirement.

2025-11-07

How to implement the conversion of the first letter to uppercase or all uppercase of the string in AnQiCMS template?

In website content presentation, the case format of strings often needs to be flexibly adjusted according to different scenarios, such as the first letter of the article title in uppercase, the username in all lowercase, or the brand name in all uppercase.AnQiCMS as a feature-rich enterprise-level content management system, its template engine provides convenient and powerful filters (Filters), which help us easily implement the case conversion of these strings, making content display more standardized and professional.

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