In the daily operation of AnQi CMS, we often encounter situations where we need to handle data that is stored as strings but actually contains multiple values.For example, an article may store multiple keywords separated by commas, or a custom content field that needs to support multiple selections. These options are finally connected into a string with a specific symbol.In this case, we often need to 'split' these strings into independent segments using a predefined delimiter, so that they can be displayed flexibly on the page or further processed.

The Anqi CMS is an efficient architecture based on the Go language, and it adopts syntax similar to the Django template engine, which provides us with powerful content rendering capabilities.In this template system, there is a very practical feature called "Filters".By cleverly using these filters, we can easily achieve the need to split strings into arrays.

KnowsplitFilter: The core tool for string splitting

In the template system of AnQi CMS,splitThe filter is a powerful tool for solving the problem of splitting strings into arrays.The function is very intuitive: it splits a string into an array of multiple elements (or, in programming terms, a slice) based on the delimiter you specify.

Basic usage method:

splitThe usage of the filter is very concise, you just need to pass the string to be processed through the pipe character|Pass tosplitthe filter, and use the colon:specify your delimiter.

{{ 您的字符串变量 | split:"分隔符" }}

For example, suppose we have a tag field in an article.archive.Tagswith the value"SEO,内容营销,网站优化,用户体验"If we want to list these tags one by one, we can do it like this:

{% set tagsString = "SEO,内容营销,网站优化,用户体验" %}
{% set tagsArray = tagsString | split:"," %}

<div class="article-tags">
    {% for tag in tagsArray %}
        <span class="tag-item">{{ tag }}</span>
    {% endfor %}
</div>

In this code, we firstsetTags define atagsStringSimulating data using a variable, then usesplit:","Split this string according to a comma,Into an array namedtagsArrayThen, we can useforLoop through thistagsArrayto independently display each tag.

The flexibility of delimiters:

splitThe filter is very flexible when handling delimiters.

  • Multiple characters as delimiters:If your delimiter is composed of multiple characters, for example" || "You can also specify directly.
    
    {% set keywordsString = "GoLang || AnQiCMS || 模板开发" %}
    {% set keywordsArray = keywordsString | split:" || " %}
    {# 结果:["GoLang", "AnQiCMS", "模板开发"] #}
    
  • The delimiter does not exist:If specifiedThe delimiter cannot be found in the string,splitThe filter will not throw an error, but will return an array containing only the original string itself.
    
    {% set text = "安企CMS是一个优秀的系统" %}
    {% set result = text | split:"," %}
    {# 结果:["安企CMS是一个优秀的系统"] #}
    
  • Empty delimiter:If you set the delimiter to an empty string"",splitThe filter will treat each UTF-8 character in the string as a separate element when splitting, even Chinese characters will be split individually.
    
    {% set chineseText = "你好世界" %}
    {% set charsArray = chineseText | split:"" %}
    {# 结果:["你", "好", "世", "界"] #}
    

Another splitting method:make_listFilter

Exceptsplitbeyond that, the Anqi CMS also providesmake_lista filter. This filter is different fromsplitthe functionality, itdoes not require a delimiterThe string is directly split into an array of individual elements, regardless of whether they are English, numbers, or Chinese characters.

Usage:

{{ 您的字符串变量 | make_list }}

When you need to process each character of a string individually,make_listthe filter will be very convenient.

{% set slogan = "AnQiCMS" %}
{% set charList = slogan | make_list %}

<p>口号分解:
    {% for char in charList %}
        <span>{{ char }}</span>
    {% endfor %}
</p>
{# 结果:口号分解:A n Q i C M S #}

What can you do after cutting it into an array?

once you have passed throughsplitormake_listThe string has been successfully converted into an array, and the template system of AnQi CMS provides you with rich subsequent processing capabilities:)

  1. Traverse the array:The most common operation is to useforLoop through the array and display each element independently.

    {% for item in mySplittedArray %}
        <li>{{ item }}</li>
    {% endfor %}
    

    You can also get the index of the current element or the number of remaining elements in the loop, for example.forloop.Counterandforloop.Revcounter.

  2. Get the length of the array:UselengthThe filter can easily obtain the number of elements in the array.

    {% set count = mySplittedArray | length %}
    <p>共有 {{ count }} 个项目。</p>
    
  3. Get the first or last element:If you only need the first or last element of the array,firstandlastFilter.

    <p>第一个元素:{{ mySplittedArray | first }}</p>
    <p>最后一个元素:{{ mySplittedArray | last }}</p>
    
  4. Recombine array into a string:Sometimes, you may need to recombine the processed array elements into a string.joinThe filter comes in handy, it issplitthe reverse operation.

    {% set newString = myProcessedArray | join:" - " %}
    <p>重新组合后的字符串:{{ newString }}</p>
    

Example of practical application scenarios

Imagine a custom field in your CMS backendProductFeaturesThe user has entered multiple features of the product, separated by a semicolon;:"防水;防尘;快充;超长待机"In the front-end page, you want to display these features as list items with small icons.

{# 假设 product.ProductFeatures 变量值为 "防水;防尘;快充;超长待机" #}
{% set featuresString = product.ProductFeatures %}
{% set featuresArray = featuresString | split:";" %}

{% if featuresArray %}
<ul class="product-features-list">
    {% for feature in featuresArray %}
        <li>
            <i class="icon-check"></i>
            <span>{{ feature }}</span>
        </li>
    {% endfor %}
</ul>
{% endif %}

This way, even if the user on the backend only enters a simple string, the frontend can present it in a structured and beautiful form, greatly enhancing the flexibility of content display and the user experience.

The template filter of AnQi CMS provides powerful and intuitive string processing capabilities,splitThe filter is an extremely important member. Mastering these skills will enable you to manage and display website content more efficiently, making your CMS website more vivid and dynamic.


Common Questions (FAQ)

1.splitfilters andmake_listWhat are the main differences between the filters?

splitThe filter requires you to specify a delimiter, which will then split the string into multiple segments. For example,"a,b,c" | split:","You will get["a", "b", "c"].make_listThe filter does not require delimiters; it directly splits each character of the string into an independent element in an array. For example,"abc" | make_listYou will get["a", "b", "c"]Choose which filter depends on what granularity you want to split the string by.

2. If the delimiter I use does not exist in the string,splitwhat result will the filter return?

When the specified delimiter is not found in the original string,splitthe filter will not return an error but instead will return an array with a single element containing the original string itself. For example,"Hello World" | split:","it will return["Hello World"]This means that your template code does not need any additional error judgment when handling such cases and can directly iterate over this array containing a single element.

How to get the first or last element of an array after slicing, instead of traversing the entire array?

In the template of Anqi CMS, ifmyArrayis already passedsplitormake_listThe array obtained, you can use it directly.firstandlastThe filter to get specific elements. For example,{{ myArray | first }}will return the first element of the array,{{ myArray | last }}while it returns the last element. This is better than usingforLoop through and judgeforloop.CounterTo get more concise.