How to iterate and display array elements in a template after splitting a string with the `split` filter?

Calendar 👁️ 71

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["你", "好", "世", "界"].

Related articles

If the delimiter parameter of the `split` filter is empty, how will it split a Chinese string?

In Anqi CMS template development, the `split` filter is a very practical tool that can help us flexibly handle string data, splitting it into an array according to the specified delimiter.This is very useful in many content display and data processing scenarios.But sometimes, under certain specific requirements, we may encounter a seemingly "blank" delimiter parameter, which raises an interesting question: What if the delimiter parameter of the `split` filter is empty, how will it cut Chinese character strings?

2025-11-08

What kind of array result will the `split` filter return when processing a string that does not contain the specified delimiter?

When developing templates on AnQiCMS, we often need to handle strings and split them into different parts for dynamic display.The `split` filter is a very practical tool that helps us split strings into arrays according to a specified delimiter.However, have you ever wondered what kind of array result the `split` filter would return when it does not find the specified delimiter in a string?This is the core issue we are going to delve into today.

2025-11-08

How to convert a comma-separated string (CSV data) into an iterable array using `split` filter?

In the daily content operation of AnQi CMS, we often encounter the need to process some data separated by specific symbols (such as commas).This data may come from custom fields, imported CSV files, or organized into a line of information specifically to keep the content concise.When we need to split these data that look like 'a whole block' into independent items that can be displayed or processed one by one, the template engine built into Anqicms provides a very practical tool - the `split` filter. `split`

2025-11-08

What is the basic usage of the `split` filter in AnQiCMS templates?

In AnQiCMS template design, flexibly handling page data is the key to building a dynamic website.Whether it is an article tag, product attribute, or other custom information, they often exist in the form of strings and need to be further split and processed.At this time, the `split` filter provided by the AnQiCMS template engine has become a very practical tool, which can help us effectively split strings into arrays, providing great convenience for subsequent data display and logic judgment.

2025-11-08

What should be noted about character encoding when using the `split` filter to cut Chinese, English, or mixed Chinese and English and numeric strings?

In AnQi CMS template development, the `split` filter is a very practical tool that helps us break down complex string data into arrays that are easier to handle.When faced with a string containing a mix of Chinese, English, and numbers, how can we ensure that the `split` filter works correctly, especially in terms of character encoding, which is a concern for many users. ### Overview of `split` filter's working principle The `split` filter is mainly used to split a string into an array according to a specified delimiter. For example

2025-11-08

How to use the `split` filter in the `{% set %}` tag to assign the sliced array to a new variable?

In AnQiCMS template development, flexibly handling and displaying data is the key to enhancing the expression of website content.We often encounter such a scenario: from the background, we get a string containing multiple pieces of information, such as keywords of articles, product feature lists, which may be separated by commas or other symbols.If it is possible to split these strings into independent segments and display or process each segment separately, it can greatly increase the flexibility of the template and the dynamism of the content.

2025-11-08

What is the difference between the `split` filter and the `make_list` filter in terms of string splitting into arrays?

In website content management, we often need to handle various data, among which string processing is particularly common.Most of the time, strings obtained from databases or user input contain multiple pieces of information, and we need to split them into independent data items for display or further processing.The template engine of AnQiCMS provides us with powerful string processing tools, where the `split` and `make_list` filters can help us convert strings into arrays, but they each have unique working methods and application scenarios.Understand the differences

2025-11-08

Will the array obtained by passing the `split` filter be identical when concatenated back into a string using the `join` filter?

In Anqi CMS template development, we often encounter scenarios where we need to process strings.The `split` and `join` filters are very commonly used tools for handling such needs.`split` can split a string into an array using a specified delimiter, while `join` can concatenate the elements of an array using a specified delimiter to form a new string.Then, when we use the `split` filter to split a string into an array and then use the `join` filter to concatenate the array back into a string

2025-11-08