In the flexible template system of AnQiCMS, we often encounter scenarios where we need to handle specific format strings.For example, an article may have multiple keywords separated by commas, or a custom data segment may be concatenated with some symbol.splitFilters andforThe combination of cycles is the powerful tool to achieve this goal.

UnderstandingsplitFilter

Imagine you have a string of keywords separated by commas, for example: "Go language, high performance, secure, flexible".If the text is output directly in the template, it will be displayed as is, lacking structure.splitThe filter comes into play. Its core function is to split a string into an array (or slice in Go language) according to the specified delimiter.

Its syntax is very intuitive: you just need to pass the string through a pipe|pass tosplitfilter, and use a colon:specify the delimiter. For example,{{ 你的字符串 | split: "分隔符" }}So, the original string will be transformed into an array containing multiple elements, each part of the split.

The actual operation of splitting a string into an array:

In AnQiCMS templates, we usually cooperatesettags to usesplitfilters to store the split array into a new variable for subsequent operations.

Assuming you set a custom field for an article in the background, namedkeywordsIts value is"网站运营,SEO优化,内容创作,用户体验". To display these keywords individually in the template, we can handle it like this:

{% set keywordString = archive.Keywords %} {# 假设 archive.Keywords 包含了 "网站运营,SEO优化,内容创作,用户体验" #}
{% set keywordArray = keywordString|split:"," %}

Here, setLabels help us create a variable namedkeywordArray.keywordStringThrough the pipe|Passing itself tosplitThe filter and specify the English comma,As a separator. After execution,keywordArrayit is no longer a single string, but an array containing four elements:["网站运营", "SEO优化", "内容创作", "用户体验"].

Here you need to pay special attention to the separator. If your string is"网站运营, SEO优化, 内容创作"After each comma, there is a space, so insplitIn the filter, you should define the delimiter as", "(Comma followed by a space) to ensure that each cut element does not contain any leading or trailing spaces, making the data cleaner.

Traverse and display array elements

Once we successfully split the string into an array, the next step is to utilizeforloop tags to iterate through the array and display each element one by one.

forLoops are a powerful tool in AnQiCMS templates used for iterating over arrays, slices, or maps. Their basic syntax is{% for item in arrayName %} ... {% endfor %}. In each iteration,itemThe variable will represent each element in the array in turn.

Following the above example, we have already obtainedkeywordArrayThis array, and now we can iterate over and display it:

<div class="tags-container">
    {% for keyword in keywordArray %}
        <span class="tag-item">{{ keyword }}</span>
    {% endfor %}
</div>

This code will be used tokeywordArrayGenerate a label for each keyword<span>And display its content. IfkeywordArrayIs["网站运营", "SEO优化", "内容创作", "用户体验"]Then the final page will display four separate<span>labels, with one keyword displayed in each label.

If your array may be empty, you can also useemptya clause to handle this situation and provide a friendly prompt:

<div class="tags-container">
    {% for keyword in keywordArray %}
        <span class="tag-item">{{ keyword }}</span>
    {% empty %}
        <p>暂无相关关键词。</p>
    {% endfor %}
</div>

So whenkeywordArrayWhen there are no elements, the page will display "No related keywords." instead of a blank space.

Complete example: from string to list tags.

Let's integrate the above steps and see an example of a more complete article tag list display:

{# 假设这是文章详情页,我们从 archive 对象中获取关键词字符串 #}
{% set rawKeywords = archive.Keywords %}

{# 使用 split 过滤器将逗号分隔的关键词字符串切割成数组 #}
{# 注意:如果关键词之间是“逗号+空格”分隔,分隔符应写成 ", " #}
{% set keywordList = rawKeywords|split:"," %}

<div class="article-tags">
    <h4>文章标签:</h4>
    <ul>
        {% for tag in keywordList %}
            {# 在这里,我们为每个标签生成一个列表项,并假设它链接到标签详情页 #}
            <li><a href="/tag/{{ tag|urlencode }}">{{ tag }}</a></li>
        {% empty %}
            <li>暂无相关标签。</li>
        {% endfor %}
    </ul>
</div>

In this example, we first start fromarchive.KeywordsExtract the original keyword string and then throughsplit:","Convert it tokeywordListArray. Then, we useforLoop throughkeywordListTo create for eachtag(Array elements) a new one<li>and<a>.{{ tag|urlencode }}Here an extra usage was madeurlencodeA filter is used to ensure that if the tag name contains special characters, it can also be passed correctly in the URL, which is a good practice.

Summary

splitThe filter is a tool in the AnQiCMS template to handle complex strings and structure them, whileforLoops are the core for traversing and displaying these structured data.By combining them, we can easily present multiple pieces of information stored in a single field flexibly on the page, whether it is article tags, product feature lists, or customized data displays, we can handle them effortlessly.Mastering this combination, you will be more efficient and skillful in content operation and template development on AnQiCMS.


Frequently Asked Questions (FAQ)

1.splitHow should the filter correctly handle spaces after delimiters?

For example, if you find that there is a space after the delimiter in the string"AnQiCMS, Go语言, 企业站"You should remove the space to ensure that each cut element does not contain extra spacessplitThe delimiter is precisely defined in the filter", "(Comma followed by a space). For example:{% set myArray = myString|split:", " %}Thus, each element will be cleanly extracted.

How do you merge the split array elements back into a string?

If you need to pass throughsplitYou can use the filtered split array elements to concatenate into a string, usingjoinfilter.joinThe filter issplitThe reverse operation, which takes an array and a separator as parameters. For example, if you have an arraymyArray, and you want to concatenate it back into a string with a comma and space, you can write it like this:{{ myArray|join:", " }}.

3. If I want to split each character of a string individually rather than by a specific delimiter, which filter should I use?

If you want to split each character (including Chinese characters, letters, numbers, symbols, etc.) in a string into an independent array element, you can usemake_lista filter. For example:{% set charArray = "你好世界"|make_list %}.charArrayIt will become["你", "好", "世", "界"].