How to split a long string into an array of strings in AnQiCMS template?

Calendar 👁️ 75

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.

Related articles

How to use the `autoescape` tag to control the automatic escaping of HTML content in AnQiCMS templates?

It is crucial to understand and effectively control the escaping behavior of HTML content during AnQiCMS template development.This not only concerns the correct display of page content, but also directly affects the security of the website, especially in preventing cross-site scripting (XSS) attacks.AnQiCMS's template system provides a flexible mechanism to manage this, with the `autoescape` tag playing a core role.

2025-11-08

escape` filter and `e` filter in AnQiCMS template are they functionally the same?

During the development of AnQiCMS templates, the security of data output is a focus we need to pay attention to.Frequently encounter issues about `escape` filter and `e` filter, many users are curious about whether there are differences in their functions.

2025-11-08

How does the AnQiCMS template escape special characters in HTML or JavaScript code to prevent XSS attacks?

When building a website with AnQiCMS, we often need to fill dynamic content into the page template, which includes text that may come from user input.However, if not handled properly, the content entered by these users may be exploited by malicious attackers to plant malicious scripts, thereby triggering cross-site scripting (XSS) attacks.XSS attacks can steal user data, tamper with page content, even hijack user sessions, causing serious harm to websites and users.AnQiCMS as a content management system that focuses on security

2025-11-08

The `dump` filter has what help for understanding complex data structures in AnQiCMS template development?

During the template development process of AnQi CMS, we often need to deal with various data passed from the backend.AnQiCMS is a powerful content model with flexible tag system, which allows us to easily obtain articles, categories, pages, and even custom fields of data.However, when the data structure becomes complex, or when we are unsure of what content a variable contains, the efficiency of development debugging will be greatly reduced.At this moment, the `dump` filter acts like a powerful 'data perspective mirror', which can help us clearly understand these complex data structures

2025-11-08

What is the type of the string array after splitting the `fields` filter in AnQiCMS template?

In AnQiCMS template development, we often need to process text content, such as splitting a string of keywords, tags, or descriptions into independent entries for list display or further operations.At this time, the `fields` filter has become a very practical tool.It can efficiently complete the splitting of strings, but many users may be curious about the data types of the split strings after the `fields` filter is applied.Understand the working mechanism of the `fields` filter

2025-11-08

How to get the string in AnQiCMS template?

In AnQiCMS template development, text and strings are the foundation for building website content.Flexible and efficient string retrieval and manipulation are skills that template developers must master, whether it is to display article titles, website names, or process user input.AnQiCMS's powerful template engine is based on Go language, providing rich tags and filters, making string acquisition and processing intuitive and practical.### Core Mechanism: Understanding the String Retrieval Method of AnQiCMS Template The most direct way to retrieve strings in AnQiCMS templates is through variable references

2025-11-08

How to display the title and content of articles in AnQiCMS templates?

Manage website content in AnQiCMS, the ultimate goal is to be able to present this content to visitors in an elegant and efficient manner.For the most common content type of articles, how to accurately display the title and body in front-end templates is a basic skill that every website operator needs to master.AnQiCMS powerful template function, providing us with a flexible and intuitive implementation method.### Core: Get to know the `archiveDetail` tag AnQiCMS's template system is designed to be very user-friendly

2025-11-08

How to implement personalized display of front-end content in AnQiCMS?

In today's era of content overload on the internet, how to make a website stand out and provide a unique and valuable experience to visitors has become crucial.The personalized display of content is an important means to enhance user stickiness, conversion rate, and brand image.AnQiCMS as an efficient and customizable content management system provides many features to help us easily achieve this goal.The flexible construction of content models: the foundation of personalized display The first step in personalized display is to make our content inherently personalized.The flexible content model feature of AnQiCMS

2025-11-08