In AnQiCMS template, how to reassemble a string array split by `split` filter using the `join` filter into a custom formatted string?

Calendar 👁️ 56

In AnQiCMS template development, dealing with string data is one of the daily tasks.Sometimes, the strings we retrieve from the database may contain multiple values separated by a specific character, such as multiple keywords of an article, which may be stored in the form of “keyword1, keyword2, keyword3”.To flexibly display this data on the front-end page, for example, turning each keyword into a clickable tag or displaying it with different delimiters, we need to use the powerful string processing filter in the AnQiCMS template—splitandjoin.

Understand the requirements of string splitting and concatenation

Imagine you are designing a template for a blog or product website.You want to display all related tags of the article at the bottom of the article detail page.These tags may be entered by the administrator into a text field in the background, separated by commas (,)Directly output the original string to the page, which will look like “AnQiCMS, template creation, content operation”, which is not aesthetic and不利于 user interaction.

At this point, the expected effect is:

  1. Split this comma-separated string into a list of individual tags (an array of strings).
  2. Process each label in the list individually, for example, by adding a link to it.
  3. Finally, reassemble the processed tags in a custom format, such as using “|” to separate, or add HTML styles to each tag.

Provided by AnQiCMSsplitandjoinThe filter is the tool to solve such problems.

UsesplitFilter: Converts a string to 'zeroing'

splitAs the name implies, a filter splits a string into an array of strings according to a specified delimiter. Its usage is very intuitive.

Basic syntax: {{ 变量名|split:"分隔符" }}

For example, we have a variablearticle.TagsIts value is"Go语言,CMS系统,AnQiCMS"We can use it like thissplitTo convert it into an array of string:

{% set rawTags = article.Tags %} {# 假设 article.Tags 的值为 "Go语言,CMS系统,AnQiCMS" #}
{% set tagArray = rawTags|split:"," %}
{# 此时,tagArray 将会是一个包含 ["Go语言", "CMS系统", "AnQiCMS"] 的数组 #}

It is worth noting that if the original string does not contain the specified delimiter,splitThe filter will return an array that only contains the original string itself. If the specified delimiter is an empty string(""It will split each character of the original string into an element of the array.

UsejoinFilter: It will gather scattered data into a heap.

withsplitThe opposite filter,joinThe filter is used to concatenate all elements of a string array into a new string using a specified delimiter.

Basic syntax: {{ 数组名|join:"拼接符" }}

Continue with the example, if we have already passedsplitgottagArrayNow, if we want to concatenate them using “|”, we can do it like this:

{% set rawTags = "Go语言,CMS系统,AnQiCMS" %}
{% set tagArray = rawTags|split:"," %}
{% set joinedTags = tagArray|join:" | " %}
{# 此时,joinedTags 的值将是 "Go语言 | CMS系统 | AnQiCMS" #}

Practical exercise: Split tags and customize the format of concatenation

Now, let's takesplitandjoinCombine to solve the problem of displaying article tags. We hope to use the article's keyword field (assumed to bearticle.Keywords, content as"AnQiCMS,模板制作,内容运营"Split, then each keyword is used as a linked tag, separated by " / ".

Template code example:

{# 假设当前页面上下文有一个名为 article 的对象,其中包含 Keywords 字段 #}

{% if article.Keywords %} {# 首先检查 Keywords 字段是否为空,避免不必要的处理和空显示 #}
    {% set keywordsString = article.Keywords %}
    {% set keywordArray = keywordsString|split:"," %} {# 使用逗号 "," 拆分字符串成数组 #}

    <div class="article-tags">
        <strong>标签:</strong>
        {% for keyword in keywordArray %} {# 遍历拆分后的关键词数组 #}
            {# 对每个关键词进行单独处理,例如生成一个带链接的标签 #}
            <a href="/tags/{{ keyword }}" class="tag-item">{{ keyword }}</a>
            {# 如果不是最后一个关键词,则添加自定义的分隔符。forloop.Last 是循环内置变量,判断是否为数组的最后一个元素 #}
            {% if not forloop.Last %}
                <span class="separator"> / </span>
            {% endif %}
        {% endfor %}
    </div>
{% endif %}

In this code, we did not use directly.joinInstead of using a filter, we go throughforManually traverse the array in a loop and add separators manually based onforloop.Lastvariables. This method is more flexible, allowing us to add complex HTML structures to each element (such as<a>Tags and custom CSS classes), not just simple string concatenation.

If you just want to simply concatenate the processed string array into a text string (without complex HTML structure), and the separator itself does not contain HTML, then you can directly usejoinFilter, the code will be more concise:

{% if article.Keywords %}
    {% set keywordsString = article.Keywords %}
    {% set keywordArray = keywordsString|split:"," %} {# 拆分 #}
    <p>关键词列表:{{ keywordArray|join:" | " }}</p> {# 拼接并显示 #}
{% endif %}

Important notes:

  • Consistency of delimiters:While usingsplitandjoinWhen, make sure the delimiter you choose is consistent in data storage and template processing. For example, if your keywords are separated by ";", then also use ";" insplit.
  • Null values and whitespace: splitThe filter will retain empty strings during processing, for example:"a,,b"Comma-separated will get:["a", "", "b"]. If the data may contain extra whitespace characters (such as"关键词1, 关键词2"), you may need to split each element after thattrimProcess to remove extra spaces.
  • The security of HTML content:If yourjoinSeparator or the array element itself may contain HTML content, and you want them to be parsed by the browser rather than displayed as plain text, remember to use it when outputting|safeFilter. For example, the abovejoinIn the example, if the delimiter|is replaced with<span class="separator"> | </span>, then you need|safeFilter to ensure<span>the tag is rendered correctly.

MasteredsplitandjoinThese powerful filters allow you to handle string data more flexibly and efficiently in the AnQiCMS template, providing users with a better website content display experience.


Frequently Asked Questions (FAQ)

Q1: Why do I usesplitSplitting the string and directly outputting the array on the page, but nothing is displayed?

A1: AnQiCMS template engine usually does not directly output the entire array object as visible text, but expects you to iterate over each element or use specific filters (such asjoinorstringformat)to format the output. If you want to view the content of the array for debugging purposes, you can use{{ 数组名|stringformat:"%#v" }}It will print the detailed structure of the variable in Go language. And when displaying on the actual page, you need to traverse and output each element like the example in the article.{% for item in 数组名 %}Loop through and output each element.

Q2: Can IsplitSplit the string and then make further modifications or filters for each element in the array?

A2: Perfectly okay.splitThe filter returns a standard string array, and you can use{% for %}Loop through each element and apply other filters to process it. For example, you can use|trimRemove the leading and trailing spaces of each tag, or use|upperConvert the label to uppercase and concatenate it into a link. This flexible combination is the strength of the AnQiCMS template.

Q3: Besides commas, which characters can I use assplitandjoinThe separator or concatenation symbol?

A3:splitandjoinThe filter accepts any string as a separator or concatenation symbol.

Related articles

How to extract and concatenate a specific field (such as Category ID) from a document list obtained through the `archiveList` tag?

When using AnQiCMS for website content management, we often need to extract specific information from the document list and combine it in some format, such as connecting a series of document category IDs into a string for front-end dynamic rendering, SEO optimization, or specific data statistics.Although AnQiCMS's template system provides powerful data acquisition capabilities, it requires us to skillfully use its built-in tags and filters to directly implement this 'extract-combine' logic in the template.### Core Challenge

2025-11-08

How does the `join` filter handle an empty array or an array with only one element in the AnQiCMS template?

In Anqi CMS template development, the `join` filter is a very practical tool that can concatenate multiple elements of an array (or list) with a specified delimiter to form a continuous string.This is very convenient when it comes to dynamically generating paths, tag lists, or any comma-separated values.In most cases, when we have an array containing multiple elements and use the `join` filter, its behavior is as expected.For example, if we have an array named `fruit_list` that contains `["apple",}

2025-11-08

When using the `join` filter, besides commas, what characters does AnQiCMS support as delimiters for joining array elements?

When developing with AnQiCMS templates, we often need to combine multiple elements in an array into a single string for display, whether it is for building navigation, displaying keywords, or formatting data lists.At this point, the `join` filter has become our helpful assistant.Many users may only be familiar with using commas (`,`) as separators, but in fact, AnQiCMS's `join` filter offers a wider range of choices, and its capabilities are far more than this.###

2025-11-08

How to connect multiple tags (Tag) in AnQiCMS template into a comma-separated keyword string?

In website operation, article tags (Tag) not only help in categorizing and retrieving content, but also enhance the page's SEO effect through keywords.Many times, we need to display multiple tags separated by commas at specific locations on the page, such as within the `<meta name="keywords">` tag or at the bottom of the article content."}AnQiCMS (AnQiCMS) provides a concise and flexible template syntax, making this operation very direct.### Understand the source of article tag data In AnQi CMS

2025-11-08

Can the `join` filter in AnQiCMS template handle array elements containing Chinese characters correctly? If so, what are the precautions?

In AnQiCMS template development, the `join` filter is a very practical tool that can concatenate all elements of an array (or slice) with a specified separator to form a single string.For many users concerned, can the `join` filter correctly handle array elements containing Chinese characters? The answer is affirmative.AnQiCMS is developed based on Go language, Go language supports UTF-8 encoding natively, which means it has a natural advantage in handling multi-language characters. Therefore

2025-11-08

What will happen when the `join` filter encounters an array with mixed data types (such as strings and numbers)?

In Anqi CMS template development, the `join` filter is a very useful tool that can help us concatenate multiple elements of a list (array) into a complete string.This is particularly convenient when it is necessary to display a series of related data in a unified format, such as displaying multiple tags of articles, multiple characteristics of products, or multiple permissions of users.However, in practice, we sometimes encounter situations where the array to be concatenated contains different types of data, such as strings, numbers, and even boolean values. So

2025-11-08

How to customize fields in the AnQiCMS backend where a field stores multiple choices (an array), and clearly display them on the frontend page using the `join` filter?

The AnQi CMS provides great convenience for website operators with its flexible content model and powerful custom features.In daily content management, we often encounter situations where we need to add multiple selection properties to articles or products, such as a product may have multiple colors, different sizes, etc.How to display them in a clear and beautiful way on the front-end page when this information is stored in the background through custom fields in the form of multi-select values has become the problem we need to solve.### Understanding the Multi-Select Custom Fields in AnQi CMS On the AnQi CMS backend

2025-11-08

In AnQiCMS template language, what are the similarities and differences between the `join` filter and other string concatenation methods, and what are their applicable scenarios?

In Anqi CMS template language, combining multiple strings or data fragments into a complete string is a very common requirement in front-end display.There are many ways to achieve this goal, each method has its unique application scenarios and advantages.Today, let's delve into the differences and similarities between the `join` filter and other commonly used string concatenation methods.### `join` filter: A bridge from array to string The `join` filter plays a very clear and efficient role in AnQiCMS template language

2025-11-08