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.