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

Calendar 👁️ 59

As an experienced expert deeply familiar with AnQiCMS operation, I know that the flexibility of content creation and display is crucial for attracting and retaining users.AnQiCMS is a powerful template engine that provides various tools for fine-grained control of content presentation, including string processing features.Today, let's delve into how to use built-in functions in the AnQiCMS template to split a string into an array using a specified delimiter, making it easier for you to display dynamic content flexibly.

In AnQiCMS template, flexibly use string splitting: convert the specified string to an array

In everyday content management, we often encounter scenarios where it is necessary to separate and independently display multiple pieces of information stored in a single text field.For example, the keywords of a document may be stored in a string separated by commas, and you want to display these keywords as independent tags or links on the front-end page.AnQiCMS template engine insplitThe filter is the tool to solve such problems.

AnQiCMS uses a template engine syntax similar to Django, one of its core advantages being the provision of rich filters (filters) to perform various operations on variables.These filters can help us to achieve data formatting and conversion at the template level without involving complex programming logic.splitThe filter is just one of many practical filters, its function is to split a string into multiple substrings based on a specified delimiter, and then organize these substrings into an array (usually represented as a slice in the Go language environment).

To usesplitA filter with a very intuitive syntax: you need to pass the string variable through a pipe|pass tosplitAnd filter,splitThen use a colon after the filter:Specify the string as a delimiter. For example, suppose we have a variabledocument.KeywordsStored with such keywords strings as “CMS, template, SEO, content management”, and we hope to split it with the separator “, ” (comma space), then in the template it can be operated like this:

{% set keyword_string = document.Keywords %} {# 假设 document.Keywords 的值为 "CMS, 模板, SEO, 内容管理" #}
{% set keyword_array = keyword_string|split:", " %}

After the above operation,keyword_arrayThis variable now stores an array containing the four elements [“CMS”, “template”, “SEO”, “content management”]

After you successfully split the string into an array, the next step is usually to traverse the array and display its content. In the AnQiCMS template,forLoop tags are very suitable for traversing arrays. CombinedsplitFilters, you can easily present the separated content one by one. For example, to present the abovekeyword_arrayThe keywords displayed as unordered list items, you can write the template code like this:

{% set keyword_string = document.Keywords %} {# 假设 document.Keywords 的值为 "CMS, 模板, SEO, 内容管理" #}
{% set keyword_array = keyword_string|split:", " %}

<p>文档相关关键词:</p>
<ul>
    {% for tag in keyword_array %}
        <li>{{ tag }}</li>
    {% endfor %}
</ul>

In practical applications, the substrings obtained after splitting may sometimes contain extra spaces (for example, if the delimiter is just a comma,Then, 'CMS, template' will be split into 'CMS' and 'template'). To ensure the content is tidy, you can use it in conjunction withtrimA filter to remove the extraneous spaces at the beginning and end of each substring. This will make your content display more standardized and beautiful:

{% set keyword_string = "CMS, 模板, SEO, 内容管理" %}
{% set keyword_array = keyword_string|split:", " %} {# 假设这里的分隔符是逗号和空格 #}

<p>文档相关关键词:</p>
<ul>
    {% for tag in keyword_array %}
        <li>{{ tag|trim }}</li> {# 使用 trim 过滤器清除多余空格 #}
    {% endfor %}
</ul>

This string splitting ability has a wide range of application scenarios in the content operation of AnQiCMS. For example, you can set the "features" field of the product detail page to be separated by a specific symbol (such as|)separated string, then cut and loop to display as product selling points; or, store multiple URLs of user-uploaded images in a custom field, throughsplitThe filter can convert these URLs into an array, thus displaying multiple images in a loop.This way greatly enhances the flexibility of the template and the ability to dynamically generate content, making your website content more interactive and visually attractive.

MastersplitThe use of filters means that you can create more dynamic and adaptable web layouts in AnQiCMS, effectively enhancing the quality and operational efficiency of content presentation.


Frequently Asked Questions (FAQ)

1. Q: How to handle extra spaces in each substring after splitting a string?

A:When usingsplitThe filter splits the string into an array and if the characteristics of the original string or delimiter cause the sub-strings at both ends to possibly contain extra spaces, you can apply it to each sub-string when iterating over the arraytrimfilter.trimThe filter can effectively remove all whitespace characters from the beginning and end of a string. For example:{{ tag|trim }}.

2. Q: If I need to split a string that does not contain the specified delimiter,splitwhat will the filter return?

A:If the string to be cut does not contain the separator you specify,splitThe filter does not cause an error, but instead returns an array containing only the original complete string as the only element. For example, ifmy_stringthe value is 'This is a single sentence' and you trymy_string|split:","The result will be a containing["这是一个单句"]array.

3. Q: In AnQiCMS templatesplitDoes the filter support regular expressions as delimiters?

A:AnQiCMS template insplitThe filter is designed to receive a plain string as a delimiter and does not directly support regular expressions.This means you cannot use complex pattern matching for splitting.If your slicing requirements involve regular expressions, you may need to consider using some processing features of the AnQiCMS backend before publishing content (such as content replacement tools) or custom development for more complex string preprocessing on the backend, and then pass the processed data to the template.

Related articles

How to truncate a string to a specified length or word count and add an ellipsis at the end?

In Anqi CMS, as an experienced website operator, we are well aware of how to enhance user experience through precise content display.In many content management scenarios, controlling the text length of article summaries, product introductions, or list page previews is a key factor in ensuring that the page is neat and beautiful, and that information is effectively communicated.In order to avoid long text affecting the layout while maintaining the continuity of the content, it is very practical in AnQiCMS template development to truncate strings to a specified length or word count and automatically add an ellipsis at the end.

2025-11-06

How to escape HTML special characters when outputting in a template to prevent XSS attacks?

As an experienced CMS website operation person in the safety industry, I know the importance of content security for website operations, especially in preventing cross-site scripting (XSS) attacks.In Anqi CMS, the template engine provides powerful tools to ensure the safety of the output content.Ensure the safety of template output: HTML special character escaping Cross-site scripting (XSS) attacks are a common security vulnerability in web applications. Attackers inject malicious client-side scripts into websites, causing browsers to execute these scripts when users browse the web.These scripts may steal user sessions

2025-11-06

How to generate random text or placeholder content for layout testing in templates?

As a senior CMS website operation personnel, I am well aware that it is crucial to carry out layout testing efficiently during the website design and development stage.When the content is not fully ready, we often need to fill in placeholder content to check the layout, style, and responsiveness of the template.AnQi CMS provides a very practical built-in tag that can help us easily generate random text.

2025-11-06

How to implement content switching and display in multilingual websites?

As an experienced website operator, I am well aware of the importance of multilingual websites in expanding the international market and enhancing the global brand influence.AnQiCMS (AnQiCMS) is a system designed specifically for enterprise-level content management, which provides us with powerful and flexible tools for building and managing global websites with built-in multilingual support.In Anqi CMS, implementing the content switching and display of a multilingual website is not just a simple text translation, but also a systematic process of content organization, template adaptation, and SEO optimization.###

2025-11-06

How to concatenate the elements of an array into a string using a specified character?

As an experienced soldier in the field of Anqing CMS content management, I know that how to efficiently handle and display data in daily operations is the key to improving website user experience and content value.AnQi CMS provides us with great flexibility with its powerful template engine.Today, we will delve deeply into a very common requirement in content display: how to concatenate multiple elements in an array into a string with a specified character.This is crucial for scenarios such as aggregating display keywords, image lists, or handling multi-select custom fields.

2025-11-06

How to remove specified characters or spaces from the beginning, end, or any position of a string?

As an experienced CMS website operation personnel for a security company, I know the importance of content quality and data cleanliness for user experience and SEO optimization.In the daily content publishing and maintenance work, we often encounter the need to clean up strings, such as removing unnecessary spaces and special characters to ensure the standardization and aesthetics of the content.

2025-11-06

How to convert English string to uppercase, lowercase, or capitalize each word?

As an experienced CMS website operation personnel for an enterprise, I know the importance of the refinement of content presentation in attracting and retaining users.When handling website content, the format of the text often determines its professionalism and readability.AnQi CMS provides a powerful and flexible template engine that can help us easily achieve various text format conversions, such as converting English strings to uppercase, lowercase, or capitalizing the first letter of each word.

2025-11-06

How to determine if a variable is empty in a template and set a default display value?

As an experienced CMS website operation person, I am well aware of the importance of template content robustness for website user experience and data display.In daily operation, we often encounter situations where variables may be empty. If not handled properly, it may result in incomplete page display, or even cause the page to report errors.AnQiCMS (AnQiCMS) offers a flexible template engine with multiple ways to determine if a variable is empty and set a default display value, which is crucial for building high-quality, high-fault-tolerant websites.

2025-11-06