`split` filter: How to split a long string into an array by a specific delimiter?

Calendar 👁️ 63

In AnQi CMS's powerful features, the flexibility of content display has always been our focus.Sometimes, you may need to enter a long string of information in a field on the back end, such as multiple keywords for an article, multiple parameters for a product specification, or a list of skills for a team member.This information is usually connected by specific delimiters (such as commas, semicolons, or vertical lines).However, when you want to display this information separately on the front-end page, even with different styles for each part, the problem arises: How can you conveniently split this long string into individual items?

At this time, the Anqi CMS template engine providessplitThe filter becomes your powerful assistant. It can cleverly split a string according to the specified delimiter into an array (or list) that can be traversed in a loop, thereby greatly enhancing the precision and flexibility of content display.

Core Function: The Secret Weapon to Split Strings into Arrays

splitThe basic function of the filter is very intuitive: it takes a string and a delimiter as parameters, and then, based on this delimiter, it "slices" the original string to generate an array containing all the independent parts.

Its usage is very concise:

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

For example, if you have a string{{ article.Keywords }}Its value is"Go语言, 安企CMS, 网站运营",You want to split it into:Go语言/安企CMSand网站运营These three independent words, you can use them like this:

{% set keywordList = article.Keywords | split:", " %}

After execution,keywordListit will become a container that includes["Go语言", "安企CMS", "网站运营"]an array. Next, you can handle each element of it as you would with other arrays and display it.

Actual application scenario: make content more flexible

splitFilters are widely used in content operation and template design, let's take a look at some common application scenarios.

Scenario one: Dynamically display article keywords or tags

When editing articles on the AnQi CMS backend, you may be accustomed to entering multiple keywords in the "Document Keywords" field, separated by commas. On the front-end page, if you want to display these keywords as independent, clickable tags,splitThe filter can be used.

Assuming your article detail page has onearchiveobject, itsKeywordsfield content is"安企CMS, 内容管理, SEO优化". You can handle it like this in the template:

<div class="article-tags">
    {% set tags = archive.Keywords | split:", " %}
    {% for tag in tags %}
        <a href="/tags/{{ tag }}" class="tag-item">{{ tag }}</a>
    {% endfor %}
</div>

By these lines of code, the original long list of keywords was split into independent tags, each with its own link and style, greatly enhancing the user experience.

Scenario two: Handling custom field data in list form

Imagine you have defined a product model in the background, with a custom field namedfeaturesUsed to store product features, the content may be"防水|防尘|抗摔".On the product detail page, you may want to display these features in a list format.

<ul class="product-features">
    {% set featureList = product.features | split:"|" %}
    {% for feature in featureList %}
        <li>{{ feature }}</li>
    {% endfor %}
</ul>

In this way, the product features can be presented clearly and logically to the user, rather than a long paragraph that is difficult to read.

In-depth Understanding: Special Cases and Sister Filters

While usingsplitWhen filtering, understanding some special cases and related sister filters can help you deal more flexibly with different content processing needs.

  1. The separator does not exist:If you specify分隔符It does not exist in the original string,splitThe filter will not throw an error but will return an array containing only the original string itself. For example,"安企CMS" | split:","You will get["安企CMS"].
  2. The delimiter is an empty string:If you set the delimiter to an empty string"",splitThe filter will be very smart in splitting each UTF-8 character of a string into an element of an array.This means that both English letters and Chinese characters are recognized individually. For example,"你好" | split:""You will get["你", "好"].

In order to split at the character level, AnQi CMS also provides a convenient sister filter:make_list. Its function is tosplitThe effect of using a space as a delimiter is similar, both are to split the string into an array of individual characters. When you know for sure that you want to split by individual characters,make_listit is a more intuitive choice.

{# 使用 split 过滤器并指定空分隔符 #}
{% set charArray1 = "安企CMS" | split:"" %}

{# 使用 make_list 过滤器 #}
{% set charArray2 = "安企CMS" | make_list %}

{# charArray1 和 charArray2 都会得到 ["安", "企", "C", "M", "S"] #}

Use examples: Hands-on practice

Below are some specific code examples to help you better understand and applysplitfilter.

{# 示例1:基本拆分与遍历 #}
{% set rawString = "Apple,Banana,Orange,Grape" %}
{% set fruits = rawString | split:"," %}
<p>水果列表:</p>
<ul>
    {% for fruit in fruits %}
        <li>{{ fruit | trim }}</li> {# 使用 trim 过滤器去除可能存在的空格 #}
    {% endfor %}
</ul>

{# 示例2:自定义字段内容的拆分与展示 #}
{# 假设 archive.Specs 为 "颜色:红色;尺寸:L;材质:棉" #}
{% set specsString = "颜色:红色;尺寸:L;材质:棉" %}
<p>产品规格:</p>
<ul>
    {% set specPairs = specsString | split:";" %}
    {% for pair in specPairs %}
        {% set detail = pair | split:":" %}
        <li><strong>{{ detail[0] }}:</strong> {{ detail[1] }}</li>
    {% endfor %}
</ul>

{# 示例3:使用空分隔符进行字符拆分 #}
{% set chineseChars = "安企CMS" %}
<p>按字符拆分:</p>
{% for char in chineseChars | split:"" %}
    <span>{{ char }}</span>
{% endfor %}

{# 示例4:使用 make_list 过滤器进行字符拆分(与示例3效果类似,更简洁) #}
<p>使用 make_list 拆分:</p>
{% for char in chineseChars | make_list %}
    <span>{{ char }}</span>
{% endfor %}

{# 示例5:当分隔符不存在时 #}
{% set singleString = "Hello AnQiCMS" %}
{% set parts = singleString | split:"," %}
<p>无分隔符拆分结果(数组长度为1):{{ parts | stringformat:"%#v" }}</p>

Summary: Unlock new potential of content management

splitThe filter is a seemingly simple but extremely powerful tool in the Anqi CMS template engine.It allows you to easily deconstruct those string data stored in a specific format into independently operable arrays.Whether it is to split keywords into independent tags for SEO optimization or to display product features one by one for aesthetic reasons,splitFilters can help you manage and display your website content in a more flexible and efficient way.Make good use of this technique, and you will be able to better utilize the advantages of AnQi CMS in terms of content customization and extensibility, providing users with a better and more friendly browsing experience.


Frequently Asked Questions (FAQ)

1.splitFilters andjoinWhat are the differences between filters?

splitFilters andjoinFilters are a pair of complementary functions.splitThe function is to split a long string into an array (list) using a specified delimiter; andjoinThe function is opposite; it is to connect all elements of an array (list) into a single string using a specified delimiter. Simply put,splitmeans 'split',joinIs "He".

2. UsesplitWhat type of variable do you get after the filter? Can you traverse it directly?

UsesplitThe variable you get after filtering is an array (or in Go language,sliceType).You can directly use it in the AnQi CMS template engine{% for ... in ... %}Loop tags to iterate over each element in the array, as shown in the example in the article.

3. If my string does not contain the specified delimiter,splitwhat will the filter return?

If your string does not contain the specified delimiter,splitThe filter will not throw an error. It will return an array containing only the original string itself, and the length of this array will be 1. For example, `

Related articles

What are the limitations of the `first` and `last` filters when getting the first and last elements of a string/array?

In Anqi CMS template design, the `first` and `last` filters are two concise and practical tools designed to help us quickly obtain the first or last character of a string, as well as the first or last element of an array.They perform well in handling simple data structures, but in practical applications, if their internal mechanisms are not well understood, they may encounter some unexpected behaviors.Firstly, let us understand their core functions. For string type data, `first` will return the first character, and `last` will return the last character

2025-11-08

How can you quickly get the first element of an array or the first character of a string in a template?

In Anqi CMS template development, efficiently obtaining data is the key to improving website performance and user experience.Whether it is dealing with a document list or image group obtained from the background, or operating on a common string, we often encounter the need to extract the first element of an array or the first character of a string.The Anqi CMS, based on Go language and Django template engine syntax, provides various intuitive and practical methods to achieve this goal.

2025-11-08

Check array or string length: `length_is` filter practical skills in AnQiCMS template?

When building a website, we often need to dynamically adjust the page display or execute different logic based on the length of the content.For example, if a title is too long and needs to be truncated, or if a list is empty and a prompt such as 'No content available' needs to be displayed.In AnQiCMS (AnQiCMS) template system, the `length_is` filter is exactly the tool for handling such precise length judgments.

2025-11-08

How to get the actual character length of a string (including Chinese) in Anqi CMS template?

When making website templates, we often need to control the display length of text to ensure that the page layout is beautiful and information is conveyed efficiently.For example, limit the number of characters in the article summary, ensure that the text in the navigation menu is not too long, or perform character count verification before submitting the form.The AnQi CMS template engine provides a very practical filter called `length`, which can easily obtain the actual character length of strings, arrays, or key-value pairs, and has good support for Chinese.

2025-11-08

What is the difference between the `make_list` filter and the `split` filter? When should `make_list` be used to split strings?

In AnQi CMS template development, we often need to process string data, such as splitting a long string into multiple independent parts for traversal, display, or further logical judgment.Anqi CMS provides a variety of filters (Filters) to help us complete these tasks, among which `make_list` and `split` are two commonly used string splitting tools.Although they can all convert strings to lists (or arrays), there are obvious differences in their functional focus and usage scenarios.

2025-11-08

Array concatenation into a string: Application scenarios of the `join` filter in AnQiCMS templates?

In website content management, we often encounter the need to display a set of data, such as multiple tags, multiple image URLs, or custom multiple-choice content, in a unified string format.AnQiCMS (AnQiCMS) boasts its efficient architecture based on the Go language and a flexible template engine similar to Django, providing great convenience for content display.Today, let's delve deeper into a very practical tool for handling such needs - the `join` filter.What is the `join` filter? In the AnQi CMS template world

2025-11-08

How to safely truncate the article content using the `truncatechars_html` filter without destroying the HTML structure for website SEO?

In website operation, we often need to display the concise content of articles in article lists, search results summaries, or social media shares.This concise content should not only attract users' attention, but also ensure that the complex HTML structure behind it is not damaged, in order to avoid affecting the layout and user experience.For search engine optimization (SEO), a clean and effective code structure is crucial. AnQiCMS (AnQiCMS) is an enterprise-level content management system developed based on the Go programming language, deeply understanding the pain points and needs of website operation.It not only provides multi-site management, a flexible content model

2025-11-08

Template content shows: How does the `truncatewords` filter truncate text by word count?

In the presentation of website content, we often need to condense lengthy text information to meet different layout requirements, such as displaying article summaries on list pages, brief descriptions on product cards, etc.This not only makes the page look neater, but also helps visitors quickly grasp the core information.AnQiCMS provides flexible template filters for this type of need, where the `truncatewords` filter is your powerful assistant for truncating text by word count.### A clever and concise summary, making the content clear at a glance

2025-11-08