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 individually on the page or used for other logical judgments.

After a string is successfully split into several parts, 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, whilelengthThe filter can easily obtain the length of the array after cutting. This article will explain in detail how to combine these two filters to achieve string cutting and length acquisition, and provide examples to help you better understand and apply them.

String splitting:splitThe role of the filter and its effects

In the AnQi CMS template system,splitA filter is a very practical tool that allows you to split a string into an array (or slice) based on a specified delimiter. Whether you are dealing with comma-separated lists, space-separated phrases, or any other form of structured text,splitCan be used for everything.

The basic usage is to pass the source string through a pipe symbol.|pass tosplitAnd provide a string as a delimiter. For example, if you have a string“安企CMS, 内容管理, Go语言开发”And you want to sort by,(Comma and space) split, it can be written 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 keywordsrawStringThen usesplit:", "Split it. Throughstringformat:"%T"We can seestringArrayThe type is[]string(string array), andstringformat:"%#v"It then displays 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_listit will generate[]string{"你", "好", "世", "界"}such an array. But for delimiter-based splitting needs,splitThe filter is more precise and commonly used. Regardless of which method is used, the final result is an array that can be further processed in the template.

Get the length of the array:lengthThe filter is crucial

Once we pass throughsplitThe filter successfully converts a string into an array, getting the length of this array becomes very simple. At this point, we need to use another powerful filter -length.

lengthThe filter, as the name implies, 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 element count) and key-value pairs (calculating key-value pair count).The usage is equally intuitive, simply pass the variable to be calculated for length through the pipe symbol|pass tolengthand it is done:{{ 变量 | length }}.

Now, let's takesplitandlengthCombine to answer the question 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 throughrawString|split:", "|lengthSuch a chained call allows us to directly obtain the number of elements in the cut array. When the original string is empty,splitThe filter will still return an array containing one empty string element, so its length will be1If your business logic needs to distinguish this situation, you can first determine if the original string is empty.

Practical application scenarios and advanced skills

The length of the array is widely used in actual template development.For example, you may need to dynamically adjust the page layout based on the number of values of a certain field, or perform a conditional judgment before looping through an array to avoid display issues caused by an empty array, thereby enhancing the user experience.

Scenario one: Display content dynamically based on array length

Assume 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|trima filter to remove any leading and trailing spaces that may exist on each tag, ensuring a cleaner display.

Scene two: combineforrepeatedlyemptyTag

Inforthe loop,lengthThe filter helps us verify whether the array is empty, thus combining{% empty %}The label provides 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, Anqi CMS also provideslength_isfilter.length_isis used to compare the length of a variable with a given value and return a boolean value (trueorfalseThis is applicable for scenarios requiring precise length matching:

{% 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 contained within,splitthe filter meetslengthThe combination of filters is your best choice. This combination is not only concise in code but also highly efficient, capable of meeting your data processing needs in various content operation scenarios.

Frequently Asked Questions (FAQ)

1