In the template design of AnQi CMS, dynamically obtaining the total length of strings, arrays, or key-value pairs is a very practical feature. It 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 template engine of AnQi CMS provides concise and efficient filters to meet these requirements.

core tools:lengthFilter

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

1. Get the character length of a string:When processing a text, sometimes it is necessary to know how many characters it contains. This is very useful in scenarios such as limiting the number of characters in an introduction, displaying the length of article titles, etc. The Anqi CMSlengthFilter can correctly recognize Chinese characters and calculate the number of characters according to UTF-8 encoding.

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

{{ articleTitle|length }}

This code will output11, because it contains 11 characters (including Chinese and English characters).

2. Get the number of elements in an array or slice:In the templates of AnQi CMS, we often get elements from tags (such asarchiveList/categoryList/navListAn array of data is obtained, which is usually in the form of an array or a slice.Know how many elements are in these lists, which can be used to display 'Total XX articles' or for conditional judgments (for example, when the list is empty, display 'No content available').

Assuming we have gone througharchiveListan article list from the tagarchives:

{% 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 outputarchivesthe actual number of articles contained in the array.

3. Get the number of elements in a key-value pair (Map/Struct)Although the need to directly obtain the “length” of key-value pairs in templates is relatively rare, it can be very helpful to understand the number of key-value pairs contained when dealing with some complex data structures (such as custom field collections). Anqi CMS'slengthThe filter also supports calculating the number of keys for key-value pair type data.

For example, if we getarchiveParamscustom parameters of a documentparams(And set to non-sorted key-value pair form), you can obtain 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 outputparamsThe number of keys in the key-value pair.

Auxiliary judgment:length_isFilter

In addition to directly obtaining the length, sometimes we only need to judge whether the length of an object is equal to a specific value. At this time,length_isThe filter is very convenient. It takes a number as a 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:0It will determinecommentsThe length of the list is 0, thus deciding to display different prompts.

Counting for specific content:wordcountFilter

If what we care about is not the length of the characters, but the number of "words" in the article content,wordcountFilter will be your helpful assistant. It will count the number of words in a string by using space as a delimiter, especially suitable for article word count.

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

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

It is worth noting that,wordcountMainly for counting English words, 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_listFilter converts a string into an array, thenlengthFilter gets the length of an array.

For example, get the number of tags from 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:","The string will be split 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.

Summary

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


Common 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, each Chinese character is counted as 1 character, consistent with the counting method of English letters.lengthAfter the filter is processed, it will return4.

2. I want to know inforIn the loop, what is the current element number or how many elements there are in total, and how should it be implemented?InforInside the loop, you can useforloop.Counterto get the current loop count (starting from 1), andforloop.RevcounterGet the number of remaining elements in the current loop. Although the Anqi CMS template engine does not provide a direct way toforloop.lengthget the total length of the loop, you canforOutside the loop first use{{ collection|length }}To get the total length, then pass this value to the loop inside, or recalculate it inside the loop when neededcollection|length.

3. How to determine if a variable is empty (such as an empty string or an empty array)?You can combinelengthfilters andiflogical judgment tags to achieve this. For example,{% if myVariable|length == 0 %} ... {% endif %}Can determine if a variable is empty. Or use it more concisely.if not myVariable(For strings, arrays, etc., it also indicates empty or no elements in some cases).