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).