How to split a string into an array with a specified separator?

Calendar 👁️ 66

In the daily operation of AnQi CMS, we often encounter the need to process some data stored as strings but actually containing multiple values.For example, an article may store multiple keywords in a comma-separated manner, or a custom content field may need to support multiple selections, and 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 the preset delimiter so that they can be flexibly displayed on the page or further processed.

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

Get to knowsplitFilter: The core tool for string splitting

In the AnQi CMS template system,splitThe filter is exactly the tool to solve the problem of cutting strings into arrays.Its function is very intuitive: according to the delimiter you specify, split a string into an array containing multiple elements (or called slices in programming terms).

Basic usage method:

splitThe filter usage is very concise, you just need to pass the string to be processed through a pipe|pass tosplitfilter, and use a colon:Specify your delimiter.

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

For example, suppose we have a tag field in an articlearchive.TagsIts value is"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 first go throughsetTags define atagsStringUse a variable to simulate data, and then usesplit:","Split this string according to the comma,Split into a namedtagsArraythe array. Then, we can utilizeforLoop through thistagsArrayto display each tag independently.

The flexibility of the delimiter:

splitThe filter is very flexible when handling delimiters.

  • A colon used as a delimiter: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 separator does not exist:If the specifieddelimiter is not 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 separators:If you set the delimiter to an empty string"",splitThe filter will treat each UTF-8 character as an independent element when splitting strings, even Chinese characters will be split separately.
    
    {% set chineseText = "你好世界" %}
    {% set charsArray = chineseText | split:"" %}
    {# 结果:["你", "好", "世", "界"] #}
    

Another splitting method: make_listFilter

exceptsplitthe following, Anqi CMS also providesmake_listFilter. This filter is different fromsplitits function, itdoes not need to specify a delimiterInstead, it directly splits each character (whether it is English, number, or Chinese) in the string into an independent element in an array.

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 splitting it into an array?

Once you pass throughsplitormake_listSuccessfully converted a string to an array, the Anqi CMS template system provides you with rich follow-up 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 current element's index 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 get 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, you can usefirstandlastfilter.

    <p>第一个元素:{{ mySplittedArray | first }}</p>
    <p>最后一个元素:{{ mySplittedArray | last }}</p>
    
  4. Combine array into a string:Sometimes, you may need to combine the processed array elements into a single string. At this point,jointhe filter comes into play, it issplitthe inverse operation.

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

Example of practical application scenarios

Imagine your Anqi CMS backend custom fieldProductFeaturesComma separated list of product features entered by the user;bar:"防水;防尘;快充;超长待机"In the front-end page, you want to display these features as individual 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 %}

In this way, even if the user on the back-end enters only a simple string, the front-end can present it in a structured and beautiful form, greatly enhancing the flexibility of content display and the user experience.

The AnQi CMS template filter provides powerful and intuitive string processing capabilities,splitThe filter is one of the most important members. By mastering these skills, you can manage and display website content more efficiently, making your Anqicms website more vivid and dynamic.


Frequently Asked Questions (FAQ)

1.splitFilters andmake_listWhat are the main differences of the filter?

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"]Howevermake_listThe filter does not require a delimiter; it will directly split each character of the string into an independent element in the array. For example,"abc" | make_listYou will get["a", "b", "c"]. Which filter to choose depends on what granularity you want to split the string by.

2. If the delimiter I am using 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 throw an error but will return an array containing only the original string itself. For example,"Hello World" | split:","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, rather than traversing the entire array?

In Anqi CMS templates, ifmyArrayis one that has already passedsplitormake_listThe array obtained, you can use it directlyfirstandlastFilter to get specific elements. For example,{{ myArray | first }}It will return the first element of the array, while{{ myArray | last }}It will return the last element. This is better than usingforLoop through and judgeforloop.CounterTo get a more concise one.

Related articles

How to remove specific characters or HTML tags from a string?

In the daily content operation of AnQiCMS, we sometimes encounter situations where we need to finely process the content, such as removing specific characters, extra spaces, or stripping unnecessary HTML tags from the content.These operations are very critical for ensuring the neatness of content display, adapting to different front-end styles, and even for data cleaning.The AnQi CMS provides powerful template filter functions to help us efficiently complete these tasks.###

2025-11-09

How to calculate the number of times a specific keyword appears in a string or array?

In AnQiCMS content management practice, we often need to carry out refined analysis and optimization of website content.In which, calculating the number of times a specific keyword appears in an article, title, or dataset is a basic and important requirement.In order to evaluate SEO keyword density, analyze content quality, or conduct data statistics, AnQiCMS provides convenient and efficient solutions.This article will deeply explore how to utilize the built-in features of AnQiCMS to easily achieve this goal.### Core Tool: `count`

2025-11-09

How to determine if a string or array contains a specific keyword?

In AnQi CMS, efficiently identify key information in content: string and array keyword judgment techniques As a content operator, we often need to handle a large amount of text data, from article titles, content descriptions to custom fields, rich and diverse information.In order to optimize search engine (SEO), implement content intelligent recommendation, or perform simple data validation, quickly judge whether a string or array contains a specific keyword is a very practical and efficient skill.In the flexible and powerful template system of Anqi CMS, this task becomes effortless.Utilize built-in filters

2025-11-09

How to center or align a string to a specified length?

When building website content, we often need to fine-tune the text layout to ensure that the information presented is both beautiful and clear.Whether it is a list, table, product parameters, or other structured display data, maintaining visual alignment and consistency is crucial for improving user experience.Aq CMS, known for its high flexibility and ease of use as a content management system, deeply understands the importance of content presentation and has built a series of powerful template filters to help us easily align and center strings

2025-11-09

How to concatenate array elements into a string with a specified separator?

When operating a website, we often encounter the need to display a set of related data in the form of a list, such as multiple tags for articles, multiple keywords for product features, or multiple image URLs in an image library.At this time, if these scattered data elements can be integrated into a concise string and separated by specific symbols, it will greatly enhance the display effect and readability of the content.The Anqi CMS template engine provides a very practical `join` filter, which can easily meet this requirement.Understanding the `join` filter `join`

2025-11-09

How to implement automatic line break display for long text?

In website content operation, we often encounter situations where we need to display a large amount of text. If these long texts are not handled properly, they may exceed the designed container, causing chaos in page layout and severely affecting user experience.AnQi CMS provides us with flexible and powerful template functions, which can easily solve the display problem of long text, especially for automatic line breaks.### Core Strategy: Using the `wordwrap` filter to implement automatic text wrapping The template system of Anqi CMS is built-in with many practical filters (Filters), among which

2025-11-09

How to define and use custom variables in a template?

In website operation, we often need to display diverse content, which may include system preset data, as well as customized personalized information based on business needs.AnQiCMS (AnQiCMS) fully understands this need, providing flexible and diverse mechanisms, allowing you to easily define and use custom variables in templates, thus achieving precise control and personalized display of content. This article will introduce you to the various methods of defining and using custom variables in AnQiCMS templates, helping you to fully utilize these features to create websites with more expressiveness and practicality.###

2025-11-09

How to include a common header, footer, or sidebar template file?

When building a website on Anqi CMS, we often encounter the need: the header (Header), footer (Footer), or sidebar (Sidebar) appear repeatedly on multiple pages.If you copy code every time, not only is it inefficient, but maintenance and updates will also become extremely complex. 幸运的是,AnQi CMS is developed based on Go language, its template engine supports syntax similar to Django, providing a very flexible and powerful way to introduce these public template files, helping us to achieve efficient content management and maintenance.

2025-11-09