How `split` and `make_list` filters split a string into an array by a specified delimiter or character?

Calendar 👁️ 74

In Anqi CMS template development, flexibly handling string data is an essential skill for building dynamic pages.Sometimes, we need to split a long string into a data list using a specified character or string as a delimiter (which is what we usually call an array);At other times, we may need to refine the processing of each character in a string independently.AnQi CMS provides two very practical filters:splitandmake_listThey can help us easily achieve these needs.

splitFilter: Split the string by the specified delimiter

splitThe primary function of the filter, as the name implies, is to 'split'.It can split a string into multiple parts based on the separator you provide and store these parts as elements in an array.This is like us cutting a long rope at each knot, getting multiple short ropes.

Why is it practical?Imagine when the content of a field you retrieve from the background is multiple values connected by commas, semicolons, or other symbols (for example, splitThe filter can be used.

How to use it? splitThe basic syntax of the filter is{{ obj|split:"分隔符" }}.

For example, if you have a stringproducts = "Apple,Banana,Orange"And you want to split it into an array containing 'Apple', 'Banana', 'Orange', you can write it like this:

{% set productList = products|split:"," %}
{% for item in productList %}
    <li>{{ item }}</li>
{% endfor %}

This will display on the page:

  • Apple
  • Banana
  • Orange

Handling special cases:

  • The separator does not exist:If the specified delimiter does not exist in the original string,splitThe filter will not throw an error, but will treat the entire string as a single element and return an array containing only one element. For example,"Hello World"|split:","The result is["Hello World"].
  • The delimiter is an empty string:If you set the delimiter to an empty string ("")splitThe filter will split each UTF-8 character in the string into a separate element, creating an array of characters. This is very useful in certain specific scenarios, but in most cases, if you want to split by character, make_listIt would be a more intuitive choice.

make_listFilter: Split a string into an array of characters

withsplitThe filter functions are similar, but with a slightly different focus.make_listA filter that can split a string directly into an array of individual characters, without relying on any delimiter, but treating the string as a character sequence.This is like picking out each character and symbol individually.

Why is it practical?When you need to perform operations on each character of a string, such as displaying characters one by one, checking character types, or performing some special formatting,make_listit becomes particularly convenient.

How to use it? make_listThe syntax of the filter is more concise:{{ obj|make_list }}.

For example, if you have a Chinese stringgreeting = "你好安企"and you want to display each character individually, you can write it like this:

{% set charList = greeting|make_list %}
{% for char in charList %}
    <span>{{ char }}</span>-
{% endfor %}

The page may display: You-hao-an-qi-

As you can see,make_listIt treats Chinese characters as independent elements for splitting, which is very suitable for processing multilingual text.

Combined use: practical scenarios

splitandmake_listFilters do not exist independently, they are often used in combination with other template tags and filters to implement more complex string processing logic.

For example, you may first usesplitSplit out an array, and then usejoinThe filter concatenates array elements in a different way:

{% set originalString = "Apple, Banana, Orange" %}
{% set processedList = originalString|split:", " %} {# 拆分成 ["Apple", "Banana", "Orange"] #}
{% set newString = processedList|join:" - " %} {# 拼接成 "Apple - Banana - Orange" #}
<p>原始字符串: {{ originalString }}</p>
<p>处理后字符串: {{ newString }}</p>

This is very convenient when you need to reformat the display of list data.

Another example is usingmake_listcooperateforLoop to fine-tune string control, such as checking if each character is a digit:

{% set myText = "AnQiCMS2024" %}
{% for char in myText|make_list %}
    {% if char|integer %} {# 尝试将字符转换为整数,非数字会返回0 #}
        <span>数字: {{ char }}</span>
    {% else %}
        <span>字符: {{ char }}</span>
    {% endif %}
{% endfor %}

This will check each onemyTextcharacter in it and display it differently according to its type.

These two filters may seem simple, but they can play a huge role in the development of Anqi CMS templates, making it easier for you to handle string data. Whether it's splitting and displaying multiple tags on the back end, or processing user input at the character level,splitandmake_listCan provide efficient and convenient solutions.


Frequently Asked Questions (FAQ)

Q1:splitandmake_listWhat are the differences when the filter processes Chinese?A1: Yes, there are differences in processing Chinese.splitThe filter will split according to the Chinese or English character delimiter you specify.make_listThe filter does not depend on delimiters, it will split each Chinese character or English character in the string into an independent element, generating a character array. In simple terms,splitIs divided by "words or phrases".make_listIs divided by "characters".

Q2: How to traverse and display the split array?A2: Whether it issplitOrmake_listThe results after splitting are all arrays (or lists), you can use the built-in tags in Anqi CMS templates to{% for item in array_variable %}loop through and display each element in the array. For example,{% for tag in tagsString|split:"," %}<span>{{ tag }}</span>{% endfor %}.

Q3: If you want to recombine the split array into a string, which filter should you use?A3: If you need to reconnect the split array elements into a string, you can usejoinFilter. This filter is different fromsplitThe function is exactly the opposite. For example,{{ productList|join:" - " }}It will join the array["Apple", "Banana", "Orange"]into a string"Apple - Banana - Orange".

Related articles

How to slice a string or array elements within a specified range using the `slice` filter?

The AnQiCMS template engine provides rich filters, giving you great flexibility in displaying content.Among them, the `slice` filter is a very practical tool that can help you accurately extract elements within a specified range of strings or arrays, whether you want to display an article summary, limit the number of images, or handle other data segments, it can be very useful.### The working principle of the `slice` filter The syntax of the `slice` filter is concise and clear: `{{ obj|slice:"from:to" }}`

2025-11-08

How to search and replace specific keywords in the `replace` filter of the Anqi CMS template?

In the daily content management and template design of AnQi CMS, we often encounter scenarios where we need to search and replace specific content in strings.Whether it is to unify brand names, filter sensitive words, or adjust the display format of some text, manually modifying a large amount of content is undoubtedly cumbersome and inefficient.Fortunately, AnQi CMS provides a very practical template filter——`replace`, which can help us easily implement these string operations.### `replace` filter

2025-11-08

How does the `repeat` filter output a string repeated a specified number of times?

During the process of website content creation, there are times when we have the need to output a specific string multiple times, such as for visual separation, placeholder content, and quick generation of list items.In the AnQiCMS template system, the `repeat` filter provides a very practical function that can help us complete this task efficiently.This filter, as the name implies, repeats a string according to the number we specify, thus saving the trouble of manual copying and pasting, greatly enhancing the efficiency and flexibility of template writing.###

2025-11-08

How do the `removetags` and `striptags` filters remove specified or all HTML tags when processing HTML content?

In the daily content operation of AnQi CMS, we often encounter situations where we need to handle HTML content.To display plain text summaries in specific scenarios, or to standardize content output and enhance security, removing HTML tags is a common requirement.AnQi CMS provides two very practical template filters: `removetags` and `striptags`. They each have unique purposes and application scenarios, let us delve into how they help us efficiently clean HTML content.###

2025-11-08

How does the `stringformat` filter customize the formatted output of any variable like Golang's `fmt.Sprintf()`?

In content operation, the way content is presented often determines the first impression and reading experience of users.Sometimes, simple variable output cannot meet our needs for fine-grained data formatting display, such as retaining fixed decimal places for numbers or adding specific text before output.AnQi CMS provides powerful content rendering capabilities for template developers and content operators, and the `stringformat` filter is a key tool for achieving refined output.It is like the `fmt.Sprintf()` function in Go language, which can format the output of any variable according to custom specifications

2025-11-08

How to get the thumbnail version of the image according to the image address using the `thumb` filter in the Anqi CMS template?

In website content management, the effective use of images is crucial for improving user experience and page loading speed.AnQiCMS deeply understands this, providing powerful image processing functions, among which the `thumb` filter is a tool that helps us easily obtain the thumbnail version of images.Why thumbnails are so important?Imagine if all the images on your website loaded in their original high-definition large size, how heavy the page would become!

2025-11-08

How do the `trim`, `trimLeft`, and `trimRight` filters remove spaces or specific characters from the beginning or end of a string?

In website operation and content management, we often encounter the need for string processing, especially in data entry, content display, or API interaction.For example, the user may have mistakenly entered multiple spaces before and after the text box, or some data may have been sourced with unnecessary specific characters.These seemingly minor issues may affect the layout and aesthetics of the content, even causing functional abnormalities.The AnQi CMS template engine provides a series of powerful filters to help us easily deal with these string cleaning tasks.Today, let's get to know the three very practical filters: `trim`

2025-11-08

How to handle truncation and add an ellipsis when truncating text with `truncatechars` and `truncatewords` filters, including HTML content?

In the increasingly fragmented information consumption era, the way websites present content directly affects user experience.Whether it is the abstract of an article list, the preview of product introduction, or various information stream cards, we need to convey the core information within a limited space while maintaining the page's neatness and uniformity of layout.This introduces the need for text truncation. AnQiCMS, as a fully functional content management system, understands this well and provides us with a powerful text truncation filter, especially its intelligent processing capabilities for HTML content, making content operations more relaxed.

2025-11-08