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

Calendar 👁️ 69

In AnQiCMS template development, flexibly handling and displaying data is the key to enhancing the website's content presentation.We often encounter such a situation: we get a string containing multiple pieces of information from the background, such as keywords of articles, feature lists of products, which may be separated by commas or other symbols.If these strings can be cut into independent segments and each segment can be displayed or processed separately, it can greatly increase the flexibility of the template and the dynamics of the content.

Today, let's delve into how to cleverly utilize in AnQiCMS templates{% set %}with the tag andsplitFilter, splits a string into an operable array and assigns it to a new variable, thus achieving finer content control.

{% set %}Label: define your own variable.

First, let's understand{% set %}Label. It plays a very important role in the AnQiCMS template syntax, allowing you to define and assign variables within the template.This is like declaring a local variable when writing a program, where you can assign any data, whether it is a string, number, or a list, object, to a custom variable name and use it in the subsequent part of the current template.

Use{% set %}The basic syntax is very intuitive:

{% set myVariable = "这是一个字符串" %}
<p>{{ myVariable }}</p>

Here, we created a namedmyVariableThe variable is assigned a string. Its scope is limited to the current template, which can help us store intermediate results and make the template code more readable and maintainable.

splitFilter: The Power Tool of String Slicing

Next, let's introduce another main charactersplitA filter. As the name suggests,splitThe main function is to split a string into an array of strings (or a slice in Go) according to the specified delimiter.

Imagine you have a string of comma-separated keywords: "SEO, content marketing, website optimization". If you want to display them as individual clickable tags, thensplitThe filter is the tool you need.

splitThe usage of the filter is as follows:

{% set tagsString = "SEO,内容营销,网站优化" %}
{% set tagsArray = tagsString|split:"," %}

{# 此时 tagsArray 就是一个包含三个元素的数组:["SEO", "内容营销", "网站优化"] #}

There are a few things to note:

  • separator:splitThe filter needs a string as a delimiter. In the above example, we used a comma,.
  • The delimiter does not existIf the original string does not contain the specified delimiter,splitthe filter will return an array containing the original string as the only element.
  • empty delimiterIf the delimiter is an empty string,"",splitThe filter splits each character of the string into an element of the array.

Core Practice:{% set %}withsplitThe perfect combination of filters

Now, let's take{% set %}andsplitCombine the filters to create a more practical scenario: Suppose your article detail page has aarchive.KeywordsField, its content is similar to

{# 1. 获取文章的关键词字符串 #}
{% set rawKeywords = archive.Keywords %}

{# 2. 使用 split 过滤器将字符串按逗号切割成数组,并赋值给新变量 keywordList #}
{% set keywordList = rawKeywords|split:"," %}

<div class="article-tags">
    <span>相关标签:</span>
    {% if keywordList %} {# 检查数组是否为空,避免空内容显示 #}
        <ul>
            {% for keyword in keywordList %}
                {# 3. 遍历数组,并为每个关键词生成链接 #}
                {#   - trim 过滤器用于移除关键词两边的空格,因为分割后可能存在 " 关键词B" 这样的情况 #}
                {#   - urlencode 过滤器用于将关键词编码,确保作为URL参数时不会出现问题 #}
                <li><a href="/tag/{{ keyword|trim|urlencode }}">{{ keyword|trim }}</a></li>
            {% endfor %}
        </ul>
    {% else %}
        <p>暂无相关标签。</p>
    {% endif %}
</div>

In this example, we first use{% set rawKeywords = archive.Keywords %}Retrieved the original keyword string. The next critical step is{% set keywordList = rawKeywords|split:"," %}it completed the string splitting, and the split string array was assigned tokeywordListthis new variable.

Later, we go through one{% for %}Loop throughkeywordListEach keyword in the array. Inside the loop, in order to provide a better user experience and SEO friendliness, we cleverly combined withtrimFilter to remove any leading and trailing spaces from keywords as wellurlencodeFilter to ensure that the generated tag links are valid and standardized

More application scenarios and techniques

This{% set %}CombinesplitThe pattern, widely used in AnQiCMS template development, has great application value:

  1. Product attribute listIf the product model has a field that stores multiple attributes (such as "color: red, size: M, material: cotton"), you can first usesplitSplit each property pair, and then further process each property pair.
  2. User-defined fieldWhen the user enters multiple value information in the custom field in the background, you can display it flexibly on the front end in this way.
  3. Image URL list processingIf a field stores multiple image links separated by a specific character, they can be sliced and displayed in an album in a loop.

Summary

AnQiCMS's powerful template engine provides great flexibility, and{% set %}with the tag andsplitThe combination of filters is one of the keys to unlocking these potential.By converting complex string data into an easy-to-process array, you can make your website content more dynamic and refined. Whether it's building a beautiful tag cloud, clear product parameters, or implementing other personalized content layouts, you will be able to do so with ease.Master these fundamental and powerful skills to better utilize AnQiCMS for managing and presenting your website content.


Frequently Asked Questions (FAQ)

Q1: IfsplitWhat will happen if the delimiter specified by the filter does not exist in the string?

A1: If the specified delimiter is not present in the string,splitThe filter will return an array containing the original string as the only element. For example,"AnQiCMS"|split:","You will get a["AnQiCMS"]the array. When iterating over it, it will still be treated as one element, you can use{% if variable %}to check if the array is empty, thus avoiding unnecessary output.

Q2:splitHow do I handle array elements after filter cutting if they themselves contain spaces?

A2: OnsplitAfter filtering the string, if there are spaces before and after the delimiter in the original string (for example"SEO , 内容营销"), the cut elements may also contain these spaces ("SEO "and" 内容营销")。In order to get clean elements, you can use a filter while traversing the array. For example:trimFilter to remove leading and trailing spaces. For example:{{ keyword|trim }}.

Q3:splitCan the filter handle non-string types of data (such as numbers)?

A3:splitThe filter is designed to process strings. If you try to apply it to non-string data types (such as a number), it will typically try to convert the data to a string first, then cut it.However, this implicit conversion may not meet your expectations, so it is recommended to usesplitBefore the filter, make sure your input data is already of string type. If you need to operate on numeric arrays, you may need to consider other methods or preprocess the data on the backend.

Related articles

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 iterate and display array elements in a template after splitting a string with the `split` filter?

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 symbols.If we want to display these strings as independent elements on the page, for example, to create clickable tags or present them as a list, then the `split` filter and `for` loop combination provided by the AnQiCMS template is the powerful tool to achieve this goal.

2025-11-08

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

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

Can the `split` filter handle multi-character delimiters, such as splitting a string with "`||`" as the delimiter?

In website content operation, we often encounter situations where we need to process strings.For example, extract multiple tags, keywords from a text field, or split stored data according to specific rules and display them separately.The template engine of AnQiCMS (AnQiCMS) provides rich filters to help us achieve these operations, among which the `split` filter is a powerful tool for string splitting.

2025-11-08

The length of the array split by the `split` filter can be obtained through which filter?

During the template development process of AnQi CMS, we often need to handle various data, among which string processing is particularly common.For example, you may need to split a string containing multiple keywords, such as "SEO, website optimization, content marketing", by commas and spaces to display one by one on the page or perform other logical judgments.After a string is successfully split into several parts, we may need to know the number of these parts, which is the length of the array.Luckyly, Anqi CMS provides a concise and efficient filter combination to solve this problem: `split`

2025-11-08