How to get the total length of elements in a string, array, or key-value pair in AnQiCMS template?

Calendar 👁️ 76

In Anqi CMS template design, dynamically obtaining the total length of elements in strings, arrays, or key-value pairs is a very practical feature, which can help us flexibly display information on the page, such as showing the number of products, the number of comments, or adjusting the layout according to the content length.The Anqi CMS template engine provides simple and efficient filters to meet these requirements.

Core tool:lengthFilter

To obtain the total length of elements in any string, array (slice), or key-value pair (map/struct), the most direct and general method is to uselengthFilter. This filter returns the actual number of elements in the target object.

1. Get the length of a string:When we are processing a text, we sometimes need to know how many characters it contains. This is very useful in scenarios such as limiting the number of words in an introduction, displaying the length of article titles, etc. Anqi CMS'slengthThe filter can also correctly identify Chinese characters, calculating the number of characters according to UTF-8 encoding.

For example, if there is a variablearticleTitleContaining "Anqi CMS template development guide", you can use it like this to get its character length:

{{ articleTitle|length }}

This code will output11Because it contains 11 characters (including Chinese and English characters).

2. Get the number of elements in an array or slice:In the AnQi CMS template, we often extract tags such asarchiveList/categoryList/navListObtaining a series of data, which is usually in the form of an array or slice.Know how many elements are in these lists, which can be used to display 'A total of XX articles' or for conditional judgment (for example, display 'No content' when the list is empty).'

Suppose we pass througharchiveLista list of articles labeledarchives:

{% archiveList archives with limit="5" %}
    <p>当前列表包含 {{ archives|length }} 篇文章。</p>
    {% for item in archives %}
        <li><a href="{{ item.Link }}">{{ item.Title }}</a></li>
    {% empty %}
        <p>暂无文章内容。</p>
    {% endfor %}
{% endarchiveList %}

here,{{ archives|length }}it will be outputarchivesthe actual number of articles contained in the array.

3. Get the number of elements in the key-value pair (Map/Struct):Although there is relatively little need to directly obtain the 'length' of key-value pairs in templates, understanding the number of key-value pairs contained in complex data structures (such as custom field sets) can also be very helpful. Anqi CMS'slengthThe filter also supports calculating the number of keys for key-value pair type data.

For example, if we go througharchiveParamsRetrieved custom parameters of a documentparams(And set as non-sorted key-value pairs), you can get the number of parameters in this way:

{% archiveParams params with sorted=false %}
    <p>该文档共有 {{ params|length }} 个自定义参数。</p>
    {% for key, value in params %}
        <li>{{ key }}: {{ value }}</li>
    {% endfor %}
{% endarchiveParams %}

Here{{ params|length }}It will output.paramsThe number of keys in the key-value pair.

Auxiliary judgment:length_isFilter

In addition to directly obtaining the length, sometimes we just need to determine if the length of an object is equal to a specific value. At this point,length_isThe filter is very convenient. It takes a numeric parameter and returns a boolean value (TrueorFalse)

For example, to determine if the comment list is empty:

{% commentList comments with archiveId=archive.Id limit="10" %}
    {% if comments|length_is:0 %}
        <p>还没有人发表评论,快来抢沙发吧!</p>
    {% else %}
        <p>共有 {{ comments|length }} 条精彩评论:</p>
        {% for comment in comments %}
            {# 显示评论内容 #}
        {% endfor %}
    {% endif %}
{% endcommentList %}

comments|length_is:0Will judgecommentsThe list length is 0, thus determining the different prompt information to be displayed.

Counting for specific content:wordcountFilter

If we are not concerned with the length of the characters, but with the number of 'words' in the content of the article,wordcountThe filter will be your helpful assistant. It will count the number of words in a string by using spaces as separators, especially suitable for article word count.

For example, display the word count of the article content:

<p>这篇文章大约有 {{ article.Content|wordcount }} 个词。</p>

It should be noted that,wordcountMainly for English word counting, for continuous Chinese character strings, it usually treats the whole Chinese string as a 'word'.

Convert a string to an array for element counting

In some cases, you may have a string connected by a specific delimiter, and you want to get the number of these 'separated elements'. In this case, you can first usesplitormake_listThe filter converts a string to an array and then useslengthThe filter gets the length of the array.

For example, get the number of tags in a comma-separated tag string:

{% set tagString = "SEO优化,内容营销,网站运营" %}
{% set tagsArray = tagString|split:"," %}
<p>文章关联了 {{ tagsArray|length }} 个标签。</p>
{% for tag in tagsArray %}
    <span>{{ tag }}</span>
{% endfor %}

here,tagString|split:","Will split the string into an array by commas, thentagsArray|lengthYou can get the number of tags (3).make_listThe filter will split each character of the string into an array as an element.

Summary

MasterlengthAnd its related filters can greatly enhance the flexibility and dynamic display capabilities of the Anqi CMS template.Whether it is to accurately display the count, adjust the style according to the content length, or make complex logical judgments, these tools can help you build a more intelligent and user-friendly website interface.


Frequently Asked Questions (FAQ)

1.lengthCan the filter correctly calculate the length of Chinese characters?Yes,lengthThe filter can accurately calculate the length of Chinese characters. It follows UTF-8 encoding, with each Chinese character being counted as 1 character, consistent with the counting method of English letters.For example, 'Hello World' goes throughlengthThe filter will return after processing4.

2. I want to know inforHow can you implement it to find the current element in a loop or the total number of elements?InforYou can use it inside the loop,forloop.Counterto get the current loop count (starting from 1), andforloop.RevcounterTo get the number of remaining elements in the current loop. Although the Anqie CMS template engine does not provide this directlyforloop.lengthsuch a property to get the total length of the loop, but you canforUse outside the loop first{{ collection|length }}To get the total length, then pass this value to the loop inside, or recalculate it inside the loop if neededcollection|length.

How to judge whether a variable is empty (for example, a string is empty, or an array has no elements)?You can combinelengthFilters andifTo implement logical judgment tags. For example,{% if myVariable|length == 0 %} ... {% endif %}Can determine if a variable is empty. Or use it more succinctly.if not myVariable(For strings, arrays, etc., it also indicates empty or no elements in some cases).

Related articles

How to concatenate the tag array in AnQiCMS template into a string with a custom delimiter?

In AnQiCMS template development, we often need to display a set of data obtained from the database, such as the multiple tags (Tags) of articles, in a user-friendly manner rather than simply listing them.One of the most common needs is to concatenate these tags into a string with a custom separator, such as AnQiCMS's powerful template engine provides a flexible way to achieve this goal.

2025-11-08

In AnQiCMS template, how to convert a string number into an actual `integer` or `float` type?

When working with the Anqi CMS template to display content and make logical judgments, we often encounter situations where we need to perform operations on numbers.However, data obtained from a database or content model, even if it looks like a number in the background, is sometimes passed as a string (``string``) at the template level.If this is directly performed arithmetic operations or numerical comparisons, unexpected results may occur.

2025-11-08

How to find the first occurrence index of a character or substring in the AnQiCMS template?

During the process of displaying website content or template development, we often encounter situations where we need to process specific text, such as checking if a keyword exists or locating the first occurrence of a character or substring.The template engine of AnQiCMS (AnQiCMS) provides a series of powerful filters (Filters) to help us complete these tasks efficiently.Today, let's discuss how to use the `index` filter to accurately find the position index of the first occurrence of a character or substring in the AnQiCMS template.Understand

2025-11-08

How to extract specific number information from a long numeric string in AnQiCMS template?

In website operations, we often encounter scenarios where we need to handle some structured long numeric string.For example, a product code may contain the production date and batch information; an order number may imply regional codes and serial numbers; or may be a unique identifier generated by specific business logic.These long digital strings often carry rich metadata, and we may only need the numerical information at specific positions for display, filtering, or further processing.

2025-11-08

How does the AnQiCMS template automatically convert line breaks in text to HTML tags such as `<p>` or `<br>`?

In website content presentation, text formatting is often the key to determining the user's reading experience.We often encounter such needs: the text content obtained from the background database usually only contains simple newline characters (`\n`), and if it is displayed directly on the web page, the browser will not intelligently convert these newline characters into the HTML paragraph (`<p>`) or line break (`<br>`) tags we expect, causing the content to be cramped together and lose its original structure and readability.AnQiCMS (AnQiCMS) has fully considered this point in template design

2025-11-08

How to dynamically define and use small array variables for loops in AnQiCMS templates?

In AnQiCMS template development, we often need to flexibly display some small data sets according to business logic.These collections may be some custom tags, navigation items, or just some status identifiers.Although AnQiCMS provides rich tags to call background data, sometimes we want to define a small array directly in the template and loop through it to achieve finer control and simpler template code.

2025-11-08

How to convert letter combinations like 'PONGO2' into the corresponding numbers on a phone keypad?

How to easily convert letter combinations to phone number keypad digits in AnQiCMS?In daily life, we sometimes encounter some phone numbers composed of letters and numbers, for example, some companies may use memorable numbers like "999-PONGO2" for brand promotion.However, when making a phone call in reality, these letters need to be converted into the corresponding numbers on the phone keypad.For website operators, if they can automatically complete this conversion on the website front end, it will undoubtedly greatly improve the user experience.

2025-11-08

How to display the singular or plural form of a word based on the quantity value in the AnQiCMS template?

When building a website, we often encounter situations where we need to dynamically display text based on a certain quantity value.For example, when there is '1 comment', we want to display it in singular form; while for '2 comments', it should be displayed in plural form.This detail handling not only improves user experience but also shows the professionalism of the website content.If manual quantity judgment and writing if/else logic make the template code long and difficult to maintain.

2025-11-08