How to split a string into an array or concatenate array elements into a single string in a template?

Calendar 👁️ 62

During the development of Anqi CMS templates, we often encounter situations where we need to process strings, such as converting a segment of text separated by a specific symbol into a list, or concatenating multiple items in a list into a continuous text.The AnqiCMS template engine provides powerful filters (Filters) to help us easily achieve these operations, greatly enhancing the flexibility of the template.

Anqi CMS template engine basics

The AnQi CMS template engine is designed very user-friendly, similar to the Django template engine. It mainly uses double curly braces{{变量}}to output variable content, and through{% 标签 %}Structure to control the logical flow, such as conditional judgment and loops. When dealing with strings and arrays, we often use the pipeline symbol|to use various built-in filters.

Flexible string splitting into an array:splitFilter

Imagine that your website backend has a custom field to store multiple keywords for articles, separated by commas,Separate, for example, “website optimization, SEO, content marketing”. You may want to display these keywords individually in the front-end template, or use them as a list of HTML tags (<li>)Present. At this time,splitThe filter comes into play.

splitThe filter can split a string into an array of strings (or a list) according to the "delimiter" you specify. Its basic usage is very intuitive:

{{ 您的字符串变量 | split:"分隔符" }}

For example, ifitem.KeywordsContains a string like "website optimization, SEO, content marketing", you can split it into an array like this:

{% set keywordList = item.Keywords | split:"," %}

Now,keywordListIt becomes a container containing["网站优化", "SEO", "内容营销"]the array. Next, you can use the template'sforloop tags to iterate and display these keywords:

<div class="article-tags">
    {% set keywordList = item.Keywords | split:"," %}
    {% for keyword in keywordList %}
        <a href="/tag/{{ keyword | urlencode }}">{{ keyword | trim }}</a>
    {% endfor %}
</div>

In this example, we not only usedsplitand also combined withurlencodethe filter to ensure that the keywords are safe in the URL, as well astrimThe filter removes any leading and trailing spaces that may exist.

It should be noted that if the specified delimiter is not present in your string,splitThe filter will treat the entire string as a single element, returning an array containing only that string. Additionally, if the delimiter is an empty string"",splitSplit each character of the string into an independent array element.

There is another related filter ismake_list, and it is withsplitdifferent,make_listAlways split each character of a string (including Chinese characters) into individual array elements. It will be very convenient if you need to split by character rather than a specific delimitermake_list.

Concatenate array elements into a single string:joinFilter

withsplitOn the contrary,joinThe filter can concatenate all elements of an array (list) using the specified 'glue' to form a single string.This is very useful when it is necessary to display multiple options, labels, or any list data in a uniform format.

joinThe usage of the filter is as follows:

{{ 您的数组变量 | join:"拼接符" }}

Assuming you already have a namedcategoriesarray that may contain["新闻", "公告", "活动"]Such category names, now do you want to separate them with commas?Concatenate them to display:

<p>文章分类:{{ categories | join:"、" }}</p>

This will output as: "Article category: News, Announcement, Event".

If you wish to extract fromsplitThe result obtained by the filter is then reassembled, or it can be operated in chain mode:

{% set rawTags = "tag1, tag2, tag3" %}
{% set processedTags = rawTags | split:"," | join:" - " %}
<p>处理后的标签:{{ processedTags }}</p>

The above code will first split “tag1, tag2, tag3”["tag1", " tag2", " tag3"]and then use-Concatenate, finally displayed as "tag1 - tag2 - tag3". Please note.splitThe elements may contain spaces, and if you want to concatenate without extra spaces, you cansplitapply to each element aftertrima filter, or consider spaces insplitthe separator.

A notable feature is that ifjoinThe object on which the filter acts is itself a string rather than an array, it will insert the concatenation symbol you specify between each character. For example,{{ "安企CMS" | join:"-" }}will output安-企-C-M-S.

Summarization and Application

splitandjoinThe filter is a powerful tool for data conversion and formatting output in Anqi CMS template.They make it easy and efficient to extract information from structured data or to integrate fragmented information for display.No matter whether you are dealing with user input tags, multiple value options in custom fields, or need to dynamically generate specific text formats based on data, these two filters can provide great convenience.Mastering them will help you build more dynamic, flexible, and easy-to-maintain website templates.


Frequently Asked Questions (FAQ)

1.splitFilters andmake_listWhat are the differences between filters?

splitThe filter splits the string based on the delimiter you specify. For example,"a,b,c" | split:","You will get["a", "b", "c"]Howevermake_listThe filter splits each character of a string into an individual array element, regardless of whether the character is English, numeric, or Chinese characters. For example,"你好" | make_listYou will get["你", "好"]It is usually used when you have specific separators (such as commas or semicolons)splitAnd when you want to process the string character by charactermake_list.

2. How can I ensure that HTML tags are properly parsed and not displayed as plain text if they are included in the content I split or concatenate?

The AnQi CMS template engine, for security reasons, defaults to escaping the output HTML content to prevent XSS attacks. If you are sure that the split or concatenated string is safe HTML content and you want the browser to parse it as HTML elements rather than plain text, you can use it when outputting variablessafea filter. For example:{{ processedContent | safe }}Make sure the content source is trustworthy to avoid security risks.

3. If I try to usesplitWhat happens if the filter splits a string but the string does not contain the specified delimiter?

WhensplitThe filter does not raise an error when it cannot find the specified delimiter in a string; instead, it will treat the entire original string as a single element and return an array containing only this one element. For example,"Hello World" | split:","The result will be["Hello World"]This means you can still iterate over this result orjoinoperate without worrying about the program crashing.

Related articles

How to display the current year or a custom formatted current date and time in the template?

## In Anqi CMS template, flexibly display the current date and custom time format In website operations, we often need to display date and time information dynamically on the page, whether it is the current year in the copyright statement, the publication time of articles, or the countdown of activities.The AnQi CMS provides a very flexible and easy-to-use method to display the current year or a custom date and time format in templates, keeping your website content up to date and enhancing user experience.The Anqi CMS template system adopts syntax similar to the Django template engine, making the display of dynamic content intuitive

2025-11-08

How to use `{filename}` or `{catname}` in pseudo-static rules to generate SEO-friendly custom URLs for articles, categories, and single pages?

In website operation, generating SEO-friendly URL addresses for content is a key link to improving website SEO performance.A clear, keyword-rich URL not only makes the page content easy for users to understand, but also helps search engines better understand and crawl web pages.AnQiCMS provides powerful custom static rule functionality, allowing us to flexibly use variables such as `{filename}` and `{catname}` to generate highly customized URLs for articles, categories, and even single pages.### Optimize URL

2025-11-08

How to set up image resource management in AnQi CMS and support batch regeneration of thumbnails in different sizes?

In website operation, images are not only an important part of the content, but also a key factor affecting page loading speed and user experience.Efficient image management can greatly enhance the performance and maintainability of a website.AnQiCMS (AnQiCMS) is well-versed in this field, providing users with comprehensive image resource management functions, especially excelling in thumbnail settings and batch processing, making image operations more convenient and flexible.### Core Feature Overview: AnqiCMS Image Management System AnqiCMS Image Resource Center is a collection of upload, classification, editing

2025-11-08

How to reuse common HTML fragments in a template by using the `include` tag or define reusable code blocks by `macro`?

In the development and maintenance of website templates, we often encounter the need to reuse HTML code snippets or logical structures.If you always copy and paste, it is not only inefficient, but also once you need to modify it, you have to repeat the operation in multiple places, which is very prone to errors.AnQi CMS knows this point, it provides a template engine that adopts Django's syntax, through `include` tags and `macro` macro functions, allowing us to easily achieve code reuse, greatly enhancing the maintainability and development efficiency of templates.### Reuse the public HTML fragment: `include`

2025-11-08

How to find the number of occurrences or the first occurrence position of a keyword in a string on a line in a template?

In AnQi CMS template design, sometimes we may need to perform more detailed analysis and display of content, such as finding the position of the first occurrence of a specific keyword in a text, or counting how many times it appears.These requirements are very practical in aspects such as dynamic content display, information extraction, or辅助SEO.Benefiting from the template engine syntax similar to Django adopted by Anqi CMS, we can utilize its powerful filter functions to achieve these goals.Next, we will discuss how to use the built-in `index` and `count` in Anqi CMS template

2025-11-08

How to safely escape HTML code in a template to prevent XSS attacks, or force non-escaping of HTML content?

When building a website, ensuring the security of the content, especially the prevention of cross-site scripting (XSS) attacks, is a crucial aspect.AnQiCMS (AnQiCMS) provides powerful tools at the template level to manage the escaping of HTML content, thereby effectively protecting the website and its users.Understanding how to safely handle HTML code in templates is essential knowledge for every AnQi CMS user when performing content operations and template development.### Default security mechanism of AnQi CMS template The template engine of AnQi CMS adopts a design philosophy similar to Django

2025-11-08

How to determine if a string or array contains a specific keyword in a template?

In the template development of Anqi CMS, we often need to dynamically adjust the page display based on specific attributes or text fragments of the content.Determine whether a string or array contains a specific keyword is a key step in implementing this dynamic logic.AnQiCMS is a powerful Django style template engine with built-in filters, making this operation very intuitive and efficient.## Core Tool: `contain` Filter The most direct way in AnQiCMS template system is

2025-11-08

How does AnQi CMS ensure that articles are automatically displayed on the website front end at the specified time?

In the fast-paced digital content world, how to ensure that content is accurately delivered to the target audience at the right time is a challenge faced by every content operator.Manual operation is not only inefficient but may also lead to release errors due to negligence.The timed release function of AnQiCMS (AnQiCMS) is specifically designed to address this pain point, providing an intelligent and automated way to ensure that your articles are displayed accurately on the website front end at the preset time points.### Understanding the core value of scheduled publishing For content operators, scheduled publishing is not just a convenient tool

2025-11-08