During AnQiCMS template development, we often encounter situations where we need to flexibly handle data. One common requirement is to split a long string containing multiple pieces of information into an independent string array using a specific delimiter (such as a space), so that it can be displayed in a loop or further operated on.The AnQiCMS template engine provides a concise and efficient filter (Filter) feature, which can easily achieve this goal.

UnderstandingsplitFilter

The AnQiCMS template system uses a template engine syntax similar to Django, it includes various practical filters to help us process data. For the need of string splitting,splitThe filter is our powerful assistant.

splitThe core function of the filter is to split a string according to the specified delimiter into a string slice (in the context of the template, we can understand it as a string array). Its syntax is very intuitive:{{ 变量 | split:"分隔符" }}.

When you usesplitWhen filtering, you need to provide two key pieces of information:

  1. The string variable to be processed: This is the long string you want to split.
  2. separatorA character or string used to specify where a string should be split. For example, if your string is 'label1 label2 label3', then the delimiter is a space (" ")

The filter processes and returns an array containing the split substrings. If the original string does not contain the specified delimiter,splitThe filter will return an array containing a single element that is the original string itself. In addition, if an empty string is used as a delimiter ("")splitThe filter will split each character of the original string into an element of the array.

Actual operation: Split the long string into an array by spaces.

Suppose you have a document field.archive.KeywordsThe content is a space-separated keyword string, for example"AnQiCMS 模板开发 字符串处理 Go语言"Now, we hope to display these keywords as independent tags one by one on the page.

We can implement the following template code:

{% set keywordString = "AnQiCMS 模板开发 字符串处理 Go语言" %}
{# 使用 split 过滤器将字符串按空格拆分成数组 #}
{% set keywordArray = keywordString|split:" " %}

<div>
    <h4>关键词列表:</h4>
    <ul>
        {# 打印数组的原始结构,方便调试理解 #}
        <p>数组原始结构:{{ keywordArray|stringformat:"%#v"|safe }}</p>

        {# 遍历拆分后的数组,逐一展示关键词 #}
        {% for keyword in keywordArray %}
            <li>{{ keyword }}</li>
        {% endfor %}
    </ul>
</div>

In this code block:

  1. We first use{% set keywordString = "..." %}Simulated a long string variablekeywordStringIn practice, this is usually from yourarchive.Keywordsor other data fields.
  2. Next, a key step is{% set keywordArray = keywordString|split:" " %}. Here,keywordStringVariables through the pipe symbol|pass tosplitFilter, and specify the delimiter as" "(a space).splitAfter the filter is executed, it will return a string array and assign it tokeywordArrayVariable.
  3. To help you better understandkeywordArrayThe internal structure, we used{{ keywordArray|stringformat:"%#v"|safe }}.stringformat:"%#v"The filter will print the variable with detailed Go language structure, whilesafeThe filter ensures that the printed string (if it contains special characters) is not automatically escaped.
  4. Finally, we use{% for keyword in keywordArray %}Loop throughkeywordArrayEach element (that is, each keyword) should be enclosed in<li>tags to display.

After executing this template code, you will see an output similar to the following on the page:

关键词列表:
数组原始结构:[]string{"AnQiCMS", "模板开发", "字符串处理", "Go语言"}
<ul>
    <li>AnQiCMS</li>
    <li>模板开发</li>
    <li>字符串处理</li>
    <li>Go语言</li>
</ul>

In this way, you can flexibly split a long string into independent array elements and dynamically display them in the AnQiCMS template.

withmake_listComparison of filters

In AnQiCMS, there is also anothermake_listfilter that can also convert strings to arrays. However,make_listworks in a waysplitdifferent from the filter:make_listis sorted bycharacterSplit the string instead of using the specified delimiter.

For example:

{% set myString = "你好 世界" %}
{% set charArray = myString|make_list %}
{% set spaceSplitArray = myString|split:" " %}

<p>按字符拆分:{{ charArray|join:"," }}</p>
<p>按空格拆分:{{ spaceSplitArray|join:"," }}</p>

The output will be:

按字符拆分:你,好, ,世,界
按空格拆分:你好,世界

It is not difficult to find,make_listAnd spaces are also treated as a character for splitting,split:" "It accurately retains the words 'Hello' and 'World' by delimiting them with spaces. Therefore, when you need to split words by a specific delimiter (such as space, comma, etc.),splitThe filter is the better choice.

BysplitThe filter, you can flexibly handle various string data, bringing richer dynamic content display to your AnQiCMS website.

Frequently Asked Questions (FAQ)

  1. How to reassemble a split string array into a long string?You can usejoinThe filter reassembles array elements into a single string. For example, ifkeywordArrayIs an array that has been split, if you want to concatenate it with a comma and a space, you can do it like this:

    {% set keywordArray = "AnQiCMS 模板开发 字符串处理"|split:" " %}
    <p>重新拼接后的字符串:{{ keywordArray|join:", " }}</p>
    {# 输出: 重新拼接后的字符串:AnQiCMS, 模板开发, 字符串处理 #}
    
  2. How can I split a long string if it is not separated by spaces but by other symbols (such as commas)? splitThe filter is very flexible, you just need to replace the delimiter parameter with the actual symbol you are using. For example, if the string is"关键词A,关键词B,关键词C", then the delimiter should be a comma (,):

    {% set commaSeparatedString = "关键词A,关键词B,关键词C" %}
    {% set newArray = commaSeparatedString|split:"," %}
    <p>按逗号拆分:{{ newArray|join:" / " }}</p>
    {# 输出: 按逗号拆分:关键词A / 关键词B / 关键词C #}
    
  3. Splitting, I just want to get one element from the array instead of traversing all, is that okay?Of course. AnQiCMS template supports array indexing, starting from0Start. For example, to getkeywordArraythe first element (index of0), you can do this:

    {% set keywordArray = "AnQiCMS 模板开发 字符串处理"|split:" " %}
    <p>第一个关键词:{{ keywordArray[0] }}</p>
    {# 输出: 第一个关键词:AnQiCMS #}
    {% if keywordArray|length > 1 %}
    <p>第二个关键词:{{ keywordArray[1] }}</p>
    {% endif %}
    

    When accessing a specific index, it is best to first check the length of the array to avoid index out of bounds errors.