During the template development process of Anqi CMS, we often need to handle various data, among which string processing is particularly common.For example, you may need to split a string containing multiple keywords, such as 'SEO, website optimization, content marketing', by commas and spaces, so that it can be displayed one by one on the page or used for other logical judgments.
The string is successfully split into several parts, and we may need to know the number of these parts, which is the length of the array. Fortunately, Anqi CMS provides a concise and efficient combination of filters to solve this problem:splitThe filter is used to split strings, andlengthFilter can easily obtain the length of the array after slicing.This article will explain in detail how to combine these two filters to achieve string splitting and length acquisition, and provide examples to help you better understand and apply them.
Splitting strings:splitThe filter and its function
In the template system of AnQi CMS,splitFilter is a very practical tool that allows you to split a string into an array (or called a slice) based on a specified delimiter. Whether you need to process a comma-separated list, space-separated phrase, or any other form of structured text,splitCan be used in many ways.
The basic usage is to pass the source string through a pipe symbol|Pass tosplitA filter, and provide a string as a delimiter. For example, if you have a string“安企CMS, 内容管理, Go语言开发”and you want to sort according to,(Comma followed by space) can be split like this:
{% set rawString = "安企CMS, 内容管理, Go语言开发" %}
{% set stringArray = rawString|split:", " %}
<p>原始字符串:"{{ rawString }}"</p>
<p>切割后的数组(类型):{{ stringArray|stringformat:"%T" }}</p>
<p>切割后的数组内容:{{ stringArray|stringformat:"%#v" }}</p>
This code will first define a string containing keywordsrawString, and then usesplit:", "And then split it.stringformat:"%T"We can see thatstringArrayThe type is[]string(string array), andstringformat:"%#v"Then it shows the specific content of the array, for example[]string{"安企CMS", "内容管理", "Go语言开发"}.
It is worth mentioning that Anqi CMS also provides another similar filtermake_listIt is used to split a string into an array of individual characters. For example,"你好世界"|make_listwill generate[]string{"你", "好", "世", "界"}This array. But for the need to split based on a delimiter,splitThe filter is more precise and commonly used. No matter which method is used, the final result is an array that can be further processed in the template.
Get the length of the array:lengthFilters are crucial
Once we have passed throughsplitThe filter successfully converts a string into an array, and getting the length of this array becomes very simple. At this point, we need to use another powerful filter -length.
lengthFilter, as the name suggests, is used to calculate the length of a given variable.It not only applies to strings (calculating UTF-8 character count), but also perfectly supports arrays (calculating the number of elements) and key-value pairs (calculating the number of key-value pairs).|Pass tolengthas follows:{{ 变量 | length }}.
Now, let's takesplitandlengthCombine this with the problem at the beginning of the article:
{% set keywordString = "安企CMS, 内容管理, SEO优化, 网站运营" %}
{% set keywordArray = keywordString|split:", " %}
<p>原始字符串:"{{ keywordString }}"</p>
<p>切割后的数组的长度为:<strong>{{ keywordArray|length }}</strong></p>
{% set emptyString = "" %}
{% set emptyArray = emptyString|split:", " %}
<p>空字符串切割后的数组长度为:{{ emptyArray|length }}</p> {# 结果为 1,因为 split 会将空字符串视为一个元素的数组 #}
{% set singleItemString = "单个词" %}
{% set singleItemArray = singleItemString|split:", " %}
<p>包含单个词的字符串切割后的数组长度为:{{ singleItemArray|length }}</p> {# 结果为 1 #}
From the above examples, we can clearly see that,rawString|split:", "|lengthSuch a chained call allows us to directly obtain the number of elements in the sliced array. When the original string is empty,splitThe filter will still return an array containing an empty string element, so its length will be1If your business logic needs to distinguish this situation, you can first judge whether the original string is empty.
Actual application scenarios and advanced techniques
Get array length is widely used in actual template development.For example, you may need to dynamically adjust the page layout based on the number of a certain field's values, or perform conditional checks before iterating over an array to avoid display issues caused by an empty array, thus enhancing the user experience.
Scenario one: Dynamically display content based on the length of the array.
Assuming you want to display the tag list only when the article has tags:
{% set tagsString = archive.Tags|default("") %} {# 假设 archive.Tags 是一个逗号分隔的字符串,如果为空则默认为空字符串 #}
{% set tagList = tagsString|split:", " %}
{% if tagList|length > 0 and tagList[0] != "" %} {# 确保数组不为空且第一个元素不为空字符串 #}
<div class="article-tags">
<strong>相关标签:</strong>
{% for tag in tagList %}
<span class="tag-item">{{ tag|trim }}</span>{% if not forloop.Last %},{% endif %}
{% endfor %}
</div>
{% else %}
<p>暂无相关标签。</p>
{% endif %}
Here we also usedtag|trimFilter to remove any leading and trailing spaces that may exist on each tag, ensuring a cleaner display.
Scenario two: combinedforLoopingemptytags
Inforin the loop,lengthThe filter helps us verify if the array is empty, so that combined{% empty %}tags provide a more user-friendly experience:
{% set productsString = currentCategory.ProductNames|default("") %} {# 假设从分类详情获取产品名称字符串 #}
{% set productNamesArray = productsString|split:"|" %} {# 假设产品名称以 "|" 分隔 #}
<h3>本分类产品列表</h3>
<ul>
{% for productName in productNamesArray %}
<li>{{ productName|trim }}</li>
{% empty %}
<li>该分类暂无产品信息。</li>
{% endfor %}
</ul>
In this example, ifproductNamesArrayis empty,{% empty %}The content of the block will be displayed instead of showing an empty list.
Filter prompt related:length_is
Exceptlength, and the Anqi CMS also provideslength_isFilter.length_isis used to compare the length of a variable with a given value and return a boolean value (trueorfalse),Applicable to scenarios requiring precise matching of length:
{% set text = "Hello AnQiCMS" %}
{% if text|length_is:13 %}
<p>文本长度刚好是 13 个字符。</p>
{% endif %}
In summary, during the template development of Anqi CMS, when you need to split a string and obtain the number of elements it contains, splitFilter is related tolengthThe combination of filters is your best choice. This combination is not only concise in code but also efficient in execution, able to meet your data processing needs in various content operation scenarios.
Common Questions (FAQ)
1