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 `/')