How to use the `split` filter to convert the custom delimiter string returned by the Anqie CMS backend (such as "keyword1|keyword2") into an array for easy traversal?

Calendar 👁️ 72

In the practice of content management in AnQi CMS, flexibility is the key to improving efficiency and achieving personalized display.Sometimes, we encounter such a requirement: the backend returns a string of text separated by a special symbol through a custom field, for example, a product introduction may have multiple related keywords, and the backend stores them as 'keyword1|keyword2|keyword3' such a format.How can I beautifully split this string into individual keywords in the front-end template and make them easy to display or iterate over?This is built-in in the powerful template engine of AnQi CMSsplitThe filter can be put to good use.

The starting point for flexible content operation: backend custom delimiter string

The AnQi CMS allows users to customize content models and fields, which brings great convenience to content operation. You may have added a custom field named "Recommendation Tags" to the article model, and when entering in the background, to store multiple tags in a field and facilitate subsequent parsing, you chose to use a special character (such as a vertical line|comma,or semicolon;used to separate different tags. In the database, the value of this field may be something like "brand story|marketing strategy|user experience".

This storage method is concise and efficient, but we usually do not want to display this original string directly on the front-end.We may need to render each tag as a clickable badge individually, or display it independently on the list page.At this point, directly operating on the original string seems inadequate.

splitFilter: The bridge between strings and arrays

splitThe filter is the tool to solve this problem. Its core function is to split a string into an array (or list) according to the delimiter you specify.Once a string is converted into an array, the template is powerful inforLoops can be put to good use, allowing you to easily traverse each element, achieving refined display and processing.

To usesplitA filter with a very intuitive syntax:

{{ 原始字符串变量 | split:"分隔符" }}

For example, if your backend has custom fieldsarchive.CustomKeywordsIt returns:"品牌故事|营销策略|用户体验"You can use it like this:split:

{{ archive.CustomKeywords | split:"|" }}

This statement will result in an array containing three elements:["品牌故事", "营销策略", "用户体验"].

Combinesetwith the tag andforLoop: Bring the array to life

Just converting a string to an array is not enough, we need to store the result for subsequent traversal. In the Anqi CMS template engine, setThe tag is very suitable for completing this task.setThe tag allows you to define a temporary variable to store data in the template.

tosplitthe filter meetssetThe tags can be combined in this way:

{% set keyword_array = archive.CustomKeywords | split:"|" %}

Now,keyword_arrayThe variable contains the split keyword array. Next, we can usefora loop to traverse the array and process each keyword individually.

A complete example may look like this:

{# 假设 archive.CustomKeywords 的值为 "品牌故事|营销策略|用户体验" #}
{% set custom_keywords_string = archive.CustomKeywords %}

{# 使用 split 过滤器将字符串按 "|" 分隔符转换为数组 #}
{% set keyword_array = custom_keywords_string | split:"|" %}

{% if keyword_array %} {# 判断数组是否为空,避免空数组时渲染无意义的HTML #}
    <div class="tags-container">
        {% for keyword in keyword_array %} {# 遍历数组中的每一个关键词 #}
            {# 对每个关键词进行 trim 操作,去除可能存在的首尾空白字符 #}
            <a href="/search?q={{ keyword | trim }}" class="tag-item">
                {{ keyword | trim }}
            </a>
        {% endfor %}
    </div>
{% else %}
    <p>暂无相关标签。</p>
{% endif %}

In this example, we first assign the content of the custom field tocustom_keywords_stringThen proceedsplit:"|"Split it intokeyword_array. Then, usingifLabel to check if the array is empty, if not empty, then passforLoop through eachkeyword. During the iteration, we also used an extratrimA filter to remove any leading and trailing whitespace from each keyword, ensuring a tidy display and wrapping it in<a>In the tag, it points to a search page, so each keyword becomes a clickable search link.

UsesplitSome considerations for the filter.

  1. Exact matching of delimiters.:splitThe filter will strictly split according to the delimiter you provide. If your string is"关键词1, 关键词2"(comma followed by space), and you only usesplit:","to split, then the elements of the array you get will be["关键词1", " 关键词2"]where the second element will contain leading spaces. To avoid this, you need to make sure that the delimiter parameter matches the delimiter in the actual string, or use it for each element during the traversaltrimThe filter removes spaces. For example, usingsplit:", "to process comma-separated values with spaces.

  2. when the delimiter does not exist: If the original string does not contain the specified delimiter,splitThe filter will return an array containing only the original string itself. This usually fits expectations because you can still process that single element throughfora loop.

  3. Special behavior of empty delimiter: If you set the delimiter to an empty string("")splitThe filter will split each UTF8 character in the original string into a separate array element. For example,"安企CMS" | split:""You will get["安", "企", "C", "M", "S"]. If you really need to split by character, this usage will be convenient.

  4. make_listAlternativeFor purely splitting strings by individual characters, Anqi CMS also providesmake_lista filter that can achieve this purpose more succinctly, for example"你好世界" | make_listYou will get["你", "好", "世", "界"].

BysplitThe filter allows AnQi CMS users to handle formatted strings returned by the backend more flexibly, converting them into structured data lists to achieve richer and more dynamic front-end content display.This not only improves the interactivity of the website content, but also brings more possibilities for SEO optimization and user experience.


Frequently Asked Questions (FAQ)

Q1: If my keywords are separated by a comma (,),splitCan the filter still be used?

A1: Of course you can.splitThe filter supports any string as a delimiter. If your keywords are separated by 'comma+space', just change the delimiter parameter to", "for example{% set keyword_array = archive.CustomKeywords | split:", " %}. It is important that the delimiter matches the actual string you are storing. When iterating, it is still recommended to use each element to ensure that each keyword does not contain unexpected whitespace.| trimfilter.

Q2:splitHow do I create link jumps for the array elements I get?

A2: splitThe filter is responsible for converting strings to arrays. If you want each keyword to be clickable, you need to manually build the links.For example, you can define a basic search URL (such as `/')

Related articles

How to use the `join` filter to concatenate the multiple tags (array) of an Anqi CMS article into a comma-separated string output?

AnQiCMS (AnQiCMS) is loved by website operators for its flexible and efficient features.In daily content management, articles or products often associate with multiple tags (Tag), which are stored in the system in the form of an array.When we need to display these tags on the front-end page, for example, showing

2025-11-08

How to precisely control the decimal places of floating-point numbers using the `floatformat` filter in Anqi CMS, and how to implement rounding or specific rounding rules?

In a content management system, the clear presentation and precise control of data are crucial, especially when displaying amounts, percentages, or any floating-point numbers.AnQiCMS (AnQiCMS) provides a powerful template engine, where the `floatformat` filter is a powerful tool for handling the display of floating-point numbers.It can help us flexibly control the number of decimal places and implement different rounding rules according to the needs, making the digital data on the website both beautiful and accurate.

2025-11-08

How to use `integer` and `float` filters to convert string numbers in Anqi CMS templates to numeric types that can be used in mathematical operations?

During the development of Anqi CMS templates, we often encounter scenarios where we need to perform numerical operations, such as calculating the total price of goods, comparing inventory quantities, or displaying different content based on specific values.However, sometimes the data obtained from the background, even if it looks like a number, may exist in the template as a string, which prevents us from performing mathematical operations directly.

2025-11-08

How to automatically add line numbers to code blocks or list content in `linenumbers` filter in Anqie CMS to enhance readability?

In daily content creation and website operations, we often need to insert code examples, configuration lists, or detailed operation steps in articles.The characteristic of this content is that it is multi-line text, and if line numbers can be automatically added to it, it will greatly enhance the reader's reading experience and the professionalism of the content.Imagine when you need to explain a part of the code to the reader, or guide them to complete a complex setup, you can accurately mention 'See line 5 of the code' or 'In step 3', this improvement in communication efficiency is self-evident.

2025-11-08

How to split a normal string into an array of individual characters using the `make_list` filter in the Anqi CMS template for more refined text processing?

In the world of AnQi CMS templates, we often need to process content in various ways, sometimes by paragraphs, sometimes by sentences, and sometimes, we need to refine the text more finely, down to every character.When conventional string processing methods fail to meet such refined needs, the `make_list` filter can excel, as it can split a common string into an array of individual characters, providing unprecedented flexibility for template designers.

2025-11-08

How to center, left-align, and right-align Chinese string with specified width using `center`, `ljust`, and `rjust` filters in the Anqi CMS template?

When building and maintaining website content, we often need to pay attention to the visual presentation of information, especially the alignment of text content.It is particularly important to accurately control the centering, left alignment, or right alignment of strings, whether it is for the neatness and beauty of the table or to maintain visual balance within a fixed width area.AnQiCMS with its flexible and powerful template engine, provides us with several very practical filters to easily achieve this goal, even for strings containing Chinese characters.

2025-11-08

How to quickly count the number of words (or Chinese words) in the content of an article in AnQi CMS using the `wordcount` filter, for SEO or reading time evaluation?

In website operation, the quality and presentation of content are crucial.The number of words in an article not only affects its performance in search engines, but is also a key indicator for evaluating user reading experience and estimating reading time.No doubt, manually counting the number of words in content is a tedious task, especially when the amount of content is vast.Luckily, AnQiCMS (AnQiCMS) has provided us with a small yet powerful tool—the `wordcount` filter, making content word count easy. ### The Importance of Word Count in Content

2025-11-08

How to use the `wordwrap` filter in AnQi CMS template to automatically wrap long text and avoid layout chaos or overflow?

In website content operation, we often encounter situations where the text content is too long, causing page layout chaos, even overflowing the container, which seriously affects the user experience.Especially when a continuous English word without spaces or a long string of Chinese characters appears in a narrow area, the default line break mechanism of the browser may not meet our design requirements.Fortunately, AnQi CMS provides a very practical tool for template developers to elegantly solve this problem - that is the `wordwrap` filter.

2025-11-08