In AnQiCMS template development, handling 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'.splitandjoin.

Understanding the requirements for string splitting and concatenation

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

This is the effect we expect:

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

Provided by AnQiCMSsplitandjoinFilters are the tools to solve such problems.

UsesplitFilter: Convert the string “化整为零” into its component parts

splitAs the name suggests, a filter is used to split a string into an array of substrings based on a specified delimiter. Its usage is very intuitive.

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

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

{% 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 containing only 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: Gather scattered data into a cohesive whole.

WithsplitThe filter is opposite,joinThe filter is used to concatenate all elements of a string array into a new string according to the specified delimiter.

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

Continue with the above example, if we have alreadysplitgottagArray, and now 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" #}

Practice: Split tags and customize the format of concatenation

Now, let's takesplitandjoinand combine them to solve the issue of displaying article tags. We hope to display the keywords field of the article (assumed to be)article.Keywords, with the 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 piece of code, we did not use directly.joinFilter, rather than throughforLoop manually through the array, and within the loop according toforloop.LastVariables are added manually with separators. This approach is more flexible, allowing us to add complex HTML structures to each element (for example<a>Tags and custom CSS classes), not just simple string concatenation.

If you just want to concatenate the processed string array into a simple 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:When usingsplitandjoinEnsure that the delimiter you choose is consistent in data storage and template processing. For example, if your keywords are separated by ";", then insplitalso use ";".
  • Empty values and whitespace: splitFilter will retain empty strings during processing, for example:"a,,b"Comma-separated will yield:["a", "", "b"]. If the data may contain extra whitespace characters (such as"关键词1, 关键词2"),you may need to split each element after that for processingtrimto remove extra spaces.
  • Security of HTML content:If yourjoinSeparators or array elements themselves may contain HTML content, and you want them to be parsed by the browser rather than displayed as plain text. Remember to use them when outputting.|safeFilter. For example, the abovejoinIn the example, if the separator|is replaced with<span class="separator"> | </span>, then it is necessary to|safeuse a filter to ensure<span>The label is rendered correctly.

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


Common Questions (FAQ)

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

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

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

A2: Absolutely.splitThe filter returns a standard array of strings, you can in{% for %}apply other filters to each element in the loop. For example, you can use|trimRemove the whitespace before and after each tag, or use|upperConvert the tags to uppercase and then concatenate them into a link. This flexible combination is the strength of AnQiCMS templates.

Q3: Besides commas, what characters can I use assplitandjoindelimiters or concatenation symbols?

A3:splitandjoinThe filter accepts any string as delimiters or concatenation symbols.