How to split a string containing multiple tags (such as “SEO, keywords, optimization”) into an array?

Calendar 👁️ 65

In the daily operation of Anqi CMS, we often encounter scenarios where we need to flexibly display some structured information in the content.For example, when setting keywords for articles or products, we may enter a string containing multiple tags in the 'document keywords' field on the back end, such as 'SEO, keywords, optimization'.Such strings are convenient to enter, but when displayed on the front-end, we usually want to display these tags separately, even convert them into independent, clickable elements.

How can such a comma-separated label string be efficiently split into individual labels in AnQi CMS template to achieve more refined content display and interaction?

The AnQi CMS template engine provides powerful filter functions, wheresplitThe filter is the tool to solve this problem. It can help us easily split a string into an array (or called a slice) according to the specified delimiter, and then we can process each element of the array individually.

Skillfully usesplitFilter

Imagine you are setting keywords for an article about SEO and filling in the 'Document Keywords' field in the backendSEO,关键词,优化,内容营销In the article detail page, you want these words to not appear as a long string, but rather as independent small tags.

At this time,splitThe filter comes into play. Its basic usage is very intuitive:

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

For example, if you want to convertSEO,关键词,优化This string is split by comma delimiter, you can do it like this:

{% set keywordString = "SEO,关键词,优化,内容营销" %}
{% set keywordArray = keywordString|split:"," %}

In this code block:

  • We first use{% set keywordString = "..." %}defined a variablekeywordStringThis stores the original string containing all tags.
  • Then,{% set keywordArray = keywordString|split:"," %}This line of code is the core. It willkeywordStringUse the content of the variable as input, through|split:","The filter, with comma,Split a string by a delimiter, and assign the result tokeywordArray.

Now,keywordArraya variable that contains["SEO", "关键词", "优化", "内容营销"]an array of these elements.

Traverse the split array to achieve flexible display

Having this array, you can use the loop tag of Anqi CMS template{% for %}Come iterate over it and personalize each tag. To make each tag look neater, especially when manually entered and there may be unintentionally left spaces, we can also combinetrimA filter to remove the extra spaces at the ends of tags.

Here is a complete example demonstrating how to split the background input tag string and display it as clickable small tags on the page:

{% set articleTags = "SEO, 关键词 , 优化 , 内容营销 , AnQiCMS" %} {# 假设这是从文档详情获取的标签字符串,可能包含一些空格 #}
{% set tagListArray = articleTags|split:"," %}

{# 检查数组是否为空,避免渲染空标签或不必要的结构 #}
{% if tagListArray %}
<div class="article-tags-container">
    <span class="tags-label">标签:</span>
    {% for tagItem in tagListArray %}
        {# 仅显示非空且去除空格后的标签,并为每个标签添加链接或样式 #}
        {% if tagItem|trim %}
        <a href="/tag/{{ tagItem|trim }}" class="tag-button">{{ tagItem|trim }}</a>
        {% endif %}
    {% endfor %}
</div>
{% endif %}

In this code block:

  1. We first pass throughsplit:","toarticleTagsThe string was split intotagListArrayarray.
  2. {% if tagListArray %}It is used to determine if the split array contains any elements, to avoid displaying an empty container when there are no tags.
  3. {% for tagItem in tagListArray %}It will then pick out each label in the array one by one.
  4. {% if tagItem|trim %}It is a very practical judgment.|trimFilter (refer to the AnQi CMS document in thefilter-trim.mdCan remove spaces from both ends of a string. This ensures that we only process and display valid (non-empty) tags.
  5. {{ tagItem|trim }}Then apply it again when displaying the tag content.trimFilter to ensure the display is clean and tidy.
  6. Here we also wrap each tag.<a>Link, and assume./tag/{{ tagItem|trim }}This is the corresponding detail page URL for the tag, so that users can view the relevant content by clicking on the tag, which greatly enhances the interactivity and SEO friendliness of the website.

In this way, even if you enter the string in the "document keyword" field in the background isSEO, 关键词 , 优化 , 内容营销(including irregular spaces), the front-end can display neatly asSEO/关键词/优化/内容营销These independent labels.

Summary

In the Aiqi CMS, make use ofsplitThe filter splits a string containing multiple tags into an array, which is a very basic but extremely powerful content operation technique.It not only makes content display more flexible and beautiful, but also brings real benefits to the website's SEO and user experience. Accompanied bytrimFilter to clean spaces, as well as.forloop andifConditions for rendering, you will be able to build more dynamic and robust templates.


Frequently Asked Questions (FAQ)

1. If my tag string is empty (for example, no keywords are filled in the background), what will the page display?

When the tag string is empty (such as"")splitThe filter returns an array containing a single empty string ([""]) But in the above example, we added{% if tagListArray %}to check if the entire array is empty, as well as{% if tagItem|trim %}Check whether each element in the array is valid after removing spaces. This means that if the label string is empty, no labels will be displayed on the page orarticle-tags-containerThis container, keep the page neat.

2. Can I use other characters as delimiters to split strings instead of commas?

Of course you can.splitThe second parameter of the filter is the specified delimiter. If you are accustomed to using a semicolon in the background;or a vertical line|to separate tags, then you just need to change the code in,Replace with the corresponding delimiter. For example, if your tag string is `SEO;Keywords;Optimization

Related articles

How to get the number of elements in a list or key-value pair in AnQiCMS template?

AnQiCMS (AnQiCMS) makes website content display intuitive and efficient with its flexible template engine.In website operation, we often need to dynamically adjust the page layout, display different content, and even perform complex logical judgments based on the number of elements in a list or key-value pair (Map).Mastering how to obtain the number of these elements in a template is an indispensable skill for advanced customization and optimization.Luckyly, AnQiCMS template syntax provides a variety of convenient ways to help us achieve this goal.### Clever Utilization

2025-11-08

What is the difference between the `length` filter and the `length_is` filter in terms of content length judgment?

In AnQiCMS template design, we often need to judge or obtain the length of content in order to flexibly control the display of content.The `length` filter and `length_is` filter are born for this purpose.Although they are all related to 'length', in actual use, their functions and application scenarios are obviously different.Understanding these subtle differences can help us build templates more efficiently and accurately.### `length` filter: Content length 'counter' `length`

2025-11-08

How to count the character length of article titles, descriptions, or custom fields?

When managing content on AnQi CMS, we often need to pay attention to the character length of article titles, descriptions, or custom fields.This concerns not only SEO optimization, ensuring that the title and description are in line with the practices of search engines, but also affects the reading experience of users on the search results page or within the website's internal list.How can you easily count the character length of this content in Anqi CMS templates?The Anqi CMS built-in template engine provides many practical filters (filters), among which the `length` filter is our tool for counting character length

2025-11-08

What is the speciality of the `index` filter for Chinese position calculation when processing multi-language content?

## A clever approach: The unique features of `index` filter and Chinese position calculation in AnQi CMS multilingual content When managing multilingual content with AnQi CMS, the flexible use of its powerful template engine and rich filters can greatly improve content operation efficiency.Among them, the `index` filter is a very practical tool that helps us quickly locate the first occurrence of a specific substring in a string.However, when our content involves Chinese characters, the `index` filter has some unique behavior in position calculation.

2025-11-08

What is the difference between the `split` filter and the `fields` filter when splitting strings by spaces?

During the template creation process in AnQi CMS, we often encounter scenarios where we need to split strings, such as extracting keywords from a description or parsing tag strings into independent words.AnQi CMS provides the practical filters `split` and `fields`. Although they can all split strings into arrays, there are subtle and crucial differences in their working methods and application scenarios when splitting strings by spaces.### `split` filter: The versatile separator expert `split` filter

2025-11-08

How to split a Chinese sentence into an array of single characters in AnQiCMS template?

In website content operation, sometimes we need to control Chinese text more finely, such as splitting a sentence into individual characters for display, or applying different styles, animation effects to each character.This need is particularly common when creating some special UI effects, interactive content, or even text games.How does the template system help us achieve this function when using AnQiCMS to build a website?AnQi CMS uses a template engine syntax similar to Django, which provides rich built-in tags and filters for content display

2025-11-08

How to concatenate a dynamically generated array (such as an article ID list) into a URL parameter string?

In website operation and content management, we often encounter such needs: to concatenate a group of dynamically generated data (such as multiple article IDs, tag IDs, etc.) in a specific format as URL parameters, in order to filter, perform batch operations, or display more accurate content.For example, the user may have selected multiple articles for comparison on the frontend, or the backend may need to generate a URL to filter articles within a specific ID range.AnQiCMS (AnQiCMS) leverages its powerful backend performance based on the Go language and flexible Django-style template engine

2025-11-08

How to replace all old keywords with new keywords in AnQiCMS template?

During website operation, we often encounter the need to update a specific text string in a website template.This may be due to a change in brand name, which requires a unified adjustment of a product or service description, or it may simply be to correct a global spelling error.Manually search and modify these strings in all related template files, which is not only time-consuming and labor-intensive but also prone to errors.Fortunately, AnQiCMS provides a very practical template filter named `replace`, which can help us efficiently and accurately complete the batch replacement of strings

2025-11-08