What is the difference between the `split` filter and the `fields` filter when splitting strings by spaces?

Calendar 👁️ 59

During the template creation process in AnQi CMS, we often encounter scenarios where we need to split strings, such as extracting keywords from a description or parsing label strings into independent words. AnQi CMS providessplitandfieldsThese two practical filters. Although they can both split strings into arrays, they have subtle and critical differences in how they work and their application scenarios when splitting strings by spaces.

splitFilter: The Flexible Separator Expert

splitThe filter, as the name implies, is used to 'split' strings.Its strength lies in its high versatility - you can specify any delimiter you want to split the string.This means, whether it is a comma, semicolon, slash, or any other custom character,splitCan all be split according to your instructions.

For example, if you have a label string separated by commas and spaces.“SEO, 内容营销, 网站优化”, you can use|split:", "Easily split it into a container that includes“SEO”/“内容营销”/“网站优化”array.

When it comes to splitting by spaces,splitIt can also handle it, you need to explicitly tell it to use a single space as the delimiter, for example|split:" "However, there is an important detail to note: if your string contains multiple consecutive spaces,splitThe filter treats each space as a separate delimiter. This means that in the split result, you may get some empty strings. For example,"Hello World"By|split:" "After splitting, you will get["Hello", "", "World"]The empty string is caused by consecutive two spaces.This behavior may be useful in some scenarios where precise control of delimiters is required, but in most cases where extracting words, we usually want to ignore these extra empty strings.

fieldsFilter: Designed to handle spaces

Compared tosplit universality,fieldsThe filter is more focused. Its design intention is to easily extract independent 'fields' or 'words' from a text, and it defaults to splitting strings by spaces, without requiring you to specify a delimiter.

fieldsThe most significant feature of the filter is its 'intelligent' handling of spaces.It automatically treats one or more consecutive spaces as a single delimiter.This means, whether it is a single space, or like“Hello AnQiCMS”Such a string containing multiple consecutive spaces,fieldscan be cleanly and neatly split into“Hello”and“AnQiCMS”without producing any empty strings. Moreover,fieldsIt will automatically remove leading and trailing whitespace characters, ensuring you get a neat, redundant word list.

Key differences and selection guide

UnderstoodsplitandfieldsThe principle, we can better choose filters that meet our own needs.

Summary of main differences:

  • Specify delimiter: splitYou need to specify the delimiter explicitly (it can be any string);fieldsIt is not necessary to specify, it defaults and splits only by spaces (including tab characters, newline characters, and other whitespace characters).
  • Handling of consecutive separators:When multiple consecutive separators are encountered,splitMay contain empty strings in the result;fieldsWill intelligently treat consecutive spaces as separators and automatically ignore them, not producing empty strings.
  • Leading and trailing whitespace: fieldsIt will automatically remove whitespace characters from the beginning and end of a string, whilesplitit will not.

When to choosesplit:

When you need to split data precisely based on non-space characters such as commas, semicolons, dashes, and pipes,splitIt is your first choice. It provides you with complete control over delimiters, able to handle various complex structured data splitting needs.For example, parsing CSV formatted data, components of URL paths, or lists of IDs in a specific format.

When to choosefields:

When your main goal is to extract words or phrases from a natural language text and you want the filter to intelligently handle multiple consecutive spaces or leading and trailing blank characters in the text,fieldsThe filter will be a more convenient and efficient choice. It can directly return an array consisting of clean words, which is very suitable for keyword extraction, article tagging, or simple text analysis.

Actual code example

To illustrate the difference between the two more intuitively, let's look at several simple code examples:

"twig {% set textString1 = " Hello AnQiCMS World " %} {% set textString2 = "apple, banana, orange" %} {% set textString3 = "one-two-three" %}"}

Use split filter

UsesplitFilter:

Split by a single space (may produce empty strings and retain leading and trailing whitespaces):

{% set splitBySpace = textString1|split: " " %}

    {% for item in splitBySpace %}
    <li>'{{ item }}'</li> {# 注意这里使用单引号来显示字符串的实际内容,包括空字符串 #}
    {% endfor %}
    

Hello AnQiCMS World

Split by comma and space (handle non-space delimiters):

{% set splitByCommaSpace = textString2|split:", " %}

    {% for item in split
    

Related articles

How to split a string containing multiple tags (such as “SEO, keywords, optimization”) into an array?

In the daily operation of Anqi CMS, we often encounter scenarios where we need to flexibly display some structured information in the content.For example, when setting keywords for articles or products, we may enter a string containing multiple tags in the "document keywords" field in the backend, such as Such strings are convenient to enter, but when displayed on the front end, we usually hope to display these tags separately, even to convert them into independent, clickable elements.How to convert such a comma-separated tag string

2025-11-08

How to get the number of elements in a list or key-value pair in AnQiCMS template?

AnQiCMS (AnQiCMS) makes website content display intuitive and efficient with its flexible template engine.In website operation, we often need to dynamically adjust the page layout, display different content, and even perform complex logical judgments based on the number of elements in a list or key-value pair (Map).Mastering how to obtain the number of these elements in a template is an indispensable skill for advanced customization and optimization.Luckyly, AnQiCMS template syntax provides a variety of convenient ways to help us achieve this goal.### Clever Utilization

2025-11-08

What is the difference between the `length` filter and the `length_is` filter in terms of content length judgment?

In AnQiCMS template design, we often need to judge or obtain the length of content in order to flexibly control the display of content.The `length` filter and `length_is` filter are born for this purpose.Although they are all related to 'length', in actual use, their functions and application scenarios are obviously different.Understanding these subtle differences can help us build templates more efficiently and accurately.### `length` filter: Content length 'counter' `length`

2025-11-08

How to count the character length of article titles, descriptions, or custom fields?

When managing content on AnQi CMS, we often need to pay attention to the character length of article titles, descriptions, or custom fields.This concerns not only SEO optimization, ensuring that the title and description are in line with the practices of search engines, but also affects the reading experience of users on the search results page or within the website's internal list.How can you easily count the character length of this content in Anqi CMS templates?The Anqi CMS built-in template engine provides many practical filters (filters), among which the `length` filter is our tool for counting character length

2025-11-08

How to split a Chinese sentence into an array of single characters in AnQiCMS template?

In website content operation, sometimes we need to control Chinese text more finely, such as splitting a sentence into individual characters for display, or applying different styles, animation effects to each character.This need is particularly common when creating some special UI effects, interactive content, or even text games.How does the template system help us achieve this function when using AnQiCMS to build a website?AnQi CMS uses a template engine syntax similar to Django, which provides rich built-in tags and filters for content display

2025-11-08

How to concatenate a dynamically generated array (such as an article ID list) into a URL parameter string?

In website operation and content management, we often encounter such needs: to concatenate a group of dynamically generated data (such as multiple article IDs, tag IDs, etc.) in a specific format as URL parameters, in order to filter, perform batch operations, or display more accurate content.For example, the user may have selected multiple articles for comparison on the frontend, or the backend may need to generate a URL to filter articles within a specific ID range.AnQiCMS (AnQiCMS) leverages its powerful backend performance based on the Go language and flexible Django-style template engine

2025-11-08

How to replace all old keywords with new keywords in AnQiCMS template?

During website operation, we often encounter the need to update a specific text string in a website template.This may be due to a change in brand name, which requires a unified adjustment of a product or service description, or it may simply be to correct a global spelling error.Manually search and modify these strings in all related template files, which is not only time-consuming and labor-intensive but also prone to errors.Fortunately, AnQiCMS provides a very practical template filter named `replace`, which can help us efficiently and accurately complete the batch replacement of strings

2025-11-08

Can the `replace` filter be used to batch modify specific links or text in article content?

In website content operation, we often encounter such situations: a brand name has been updated, or a batch of external links have failed and need to be replaced uniformly, or the internal link structure of the website has been adjusted, and it is necessary to synchronize update the old links or text in a large number of articles.At this point, we would naturally think that the `replace` filter of AnQiCMS (AnQiCMS) can help us handle these modifications in bulk?The answer is, the `replace` filter is not used for batch modifying article content, its function is in another direction

2025-11-08