How to convert an array to a string with a delimiter, or split a string into an array?

Calendar 👁️ 87

In Anqi CMS template development, we often encounter situations where we need to handle data format conversions, especially when combining multiple values into a single string or splitting a string containing multiple values into independent data.This is especially common when dealing with tags, multiple choice properties, or extracting information from custom fields. 幸运的是,AnQi CMS内置了非常实用的模板过滤器,可以帮助我们轻松实现数组与带分隔符字符串之间的相互转换。

Convert an array to a string with a delimiter: A trick to usejoinFilter

Imagine if your article has multiple tags (Tag), they may be stored in an array or list in the database.But you want to display them on one line on the page, separated by commas or specific symbols, such as "AnQi CMS, Template Development, Content Management".joinThe filter can be used.

joinThe filter function is used to concatenate all elements of an array or list into a single string with a specified delimiter.

Its use is very intuitive:

{{ 您的数组变量 | join:"您想要的分隔符" }}

For example, suppose you have a variable namedtagsAn array that contains all the tags of the article:

{% set tags = ["安企CMS", "模板开发", "Go语言", "SEO优化"] %}
<div>
  文章标签:{{ tags | join:", " }}
</div>

It will be displayed on the page:

文章标签:安企CMS, 模板开发, Go语言, SEO优化

You can also choose other delimiters, such as a vertical line:|Or space:

<div>
  相关关键词:{{ tags | join:" | " }}
</div>

This will output:

相关关键词:安企CMS | 模板开发 | Go语言 | SEO优化

If your variable is itself a string,joinThe filter will connect each character as a separate element, which needs to be paid special attention to when handling Chinese characters:

<div>
  字符连接:{{ "安企内容管理系统" | join:"-" }}
</div>

It will be output:

字符连接:安-企-内-容-管-理-系-统

Therefore,joinA filter is an ideal tool for processing data items from multiple independent sources (usually lists or arrays) to generate an easily readable summary string.

Split a string with a delimiter into an array: ExploresplitFilter

When you get a string of values connected by a specific delimiter from a custom field, such as entering "Product A; Product B; Product C" in a text box, you may need to extract these values one by one, iterate through them, or process them independently. At this point,splitThe filter is your helpful assistant.

splitThe filter can split a string into an array of strings based on the delimiter you provide.

The basic syntax is:

{{ 您要切割的字符串 | split:"您的分隔符" }}

For example, suppose your article has a custom fieldkeywordsContaining comma-separated keywords:

{% set keywordString = "网站运营,内容营销,SEO优化,用户体验" %}
{% set keywordsArray = keywordString | split:"," %}

<ul>
  {% for keyword in keywordsArray %}
    <li>{{ keyword | trim }}</li>
  {% endfor %}
</ul>

This has been usedtrimA filter to remove any leading and trailing spaces from each keyword, ensuring the output is neat. It will be displayed as a list on the page:

- 网站运营
- 内容营销
- SEO优化
- 用户体验

Some special cases:

  • Empty separators:If you use an empty string""as a separator,splitThe filter will split each UTF-8 character (including Chinese characters) in the original string into an element of the array.

    {% set text = "你好安企" %}
    {% set charArray = text | split:"" %}
    <div>
      {% for char in charArray %}
        <span>{{ char }}</span>
      {% endfor %}
    </div>
    

    output:<span>你</span><span>好</span><span>安</span><span>企</span>

  • The separator does not exist:If the specified delimiter is not found in the original string,splitThe filter will return an array containing only the original string itself. This can be used as a simple judgment mechanism.

  • make_listFilter:Similar tosplit,make_listThe filter can also split a string into an array of characters. It has a similar effect,split:""which is to take each character of the string as an element of the array.

    {% set text = "安企CMS" %}
    {% set charList = text | make_list %}
    <div>
      {{ charList | join:"/" }}
    </div>
    

    output:安/企/C/M/S

  • fieldsFilter:If the string you are processing is purely space-separated words or phrases,fieldsThe filter provides a shortcut that defaults to splitting by spaces and returns an array of strings.

    {% set sentence = "安企 CMS 是 一个 强大的 系统" %}
    {% set wordList = sentence | fields %}
    <div>
      词组:{{ wordList | join:"-" }}
    </div>
    

    output:词组:安企-CMS-是-一个-强大的-系统

Application scenarios and tips

MasteredjoinandsplitThese filters will give you greater flexibility in content management and template development in Anqicms.

  1. Handling multi-value input of custom fields:If the background has a custom text field that allows users to enter multiple values (such as product features, service advantages), it is recommended to agree on a unified delimiter (such as a comma or semicolon) and then use it in the template.splitConvert it to an array and then useforLoop through the display.

    {# 假设 archive.ProductFeatures 是后台输入的“特点1,特点2,特点3” #}
    {% set features = archive.ProductFeatures | split:"," %}
    {% if features %}
      <div class="product-features">
        {% for feature in features %}
          <span>{{ feature | trim }}</span>
        {% endfor %}
      </div>
    {% endif %}
    
  2. Dynamically generate metadata or a tag cloud:When you need to dynamically generate based on multiple tags or keywords on a pagemetalabel'skeywordsWhen content, you can first obtain a list of all tags, and thenjoina filter will combine them.

    {% tagList tags %} {# 获取当前文档的所有标签 #}
    {% set tagTitles = [] %}
    {% for tag in tags %}
      {% set tagTitles = tagTitles | add:tag.Title %} {# 将每个标签的Title添加到新的数组 #}
    {% endfor %}
    <meta name="keywords" content="{{ tagTitles | join:"," }}">
    {% endtagList %}
    

    (Note: you can use it directly in the template)addAn element needs to be added to the array with support for this operation.addFilter or similar mechanism, AnQi CMSaddThe filter is mainly used for adding numbers or strings, and the code here is a conceptual demonstration. In actual operations, if it is necessary to dynamically construct an array, it is usually handled at the controller level.

  3. URL parameter processing:Although AnQi CMS's pseudo-static rules are very flexible, in some advanced scenarios, you may need to parse or construct a URL containing multiple parameters.splitandjoinThe filter can help when processing these parameters.

Summary

joinandsplitThe filter is a powerful tool in Anqi CMS template for handling string and array conversions, making data display and logical processing more flexible.Reasonably utilizing these features can significantly improve your efficiency in content operation and template development, allowing your website content to present in a more tailored manner to meet your needs.


Frequently Asked Questions (FAQ)

1.splitWhat happens if the filter cannot find the specified delimiter?IfsplitThe filter does not find the delimiter you specified in the string, it will not raise an error, but will return an array containing only the original string. For example,"AnQiCMS" | split:","It will return an array containing["AnQiCMS"]an array. You can handle this situation by checking the length of the array.

2. Can IjoinorsplitCan you use a variable as a delimiter in the filter?Can.The delimiter parameter can be a direct string literal or a variable that stores a delimiter string.This allows you to dynamically adjust the delimiter based on different content or context.{{ my_array | join:my_delimiter_variable }}.

3.splitThe filter, when cutting a string containing Chinese characters, is it cutting by character or by byte? splitBy default, the filter cuts according to the delimiter you provide. If an empty string is used""As a separator, it will split according to UTF-8 encoding, which means a Chinese character is treated as a separate splitting unit, not split by bytes. Therefore,"你好" | split:""You will get["你", "好"].

Related articles

How to perform simple number or string concatenation in AnqiCMS template?

In Anqi CMS template design, flexibly handling and displaying data is the key to building a dynamic website.This is a common need in daily development to concatenate numbers or strings.AnQi CMS provides various ways to achieve this goal, from simple direct combinations to powerful filters, which can meet your different content assembly scenarios.Understanding the Basics of Concatenation: Direct Output Equivalent to "Addition" In Anqi CMS template syntax, the most intuitive way to concatenate strings is to place multiple variables or text directly side by side. For example

2025-11-08

How to remove leading and trailing spaces or specified characters from a string?

In website content management, string formatting is often a problem we need to solve when displaying content and handling data.Especially in user input, data import, or system-generated content, strings may have extraneous spaces at the beginning and end, or specific characters may need to be removed to meet expected display effects or data standards.AnQiCMS as an efficient and flexible content management system, through its powerful template engine and rich filters, provides us with concise and powerful string processing capabilities, allowing such tasks to be easily completed at the template level.

2025-11-08

How to format numbers in Anqi CMS (such as retaining decimal places for floating-point numbers)?

In website operation, the way data is displayed is crucial to user experience.Whether it is product prices, statistics, or financial statements, clear and standardized number formats can not only enhance the professionalism of the website but also help users understand information more intuitively.AnQi CMS knows this need, and provides powerful number formatting functions in the template system, allowing us to easily control the decimal places of floating-point numbers, the display style of integers, and more customized presentations of numbers.### Why is Number Formatting So Important? Imagine a e-commerce website where the price of a product is displayed as "199"

2025-11-08

How to automatically convert a URL string to a clickable link in a template?

In website content operation, we often encounter such situations: articles, introductions, or comments contain some URL strings that can be seen by users but cannot be directly clicked to jump, which not only affects user experience but also reduces the readability and practicality of the content.As an AnQiCMS user, you will find that the system provides us with a set of elegant and efficient solutions that can easily convert these ordinary URL strings into clickable links.AnQiCMS's template engine is powerful and flexible, it draws on the concise syntax of Django templates

2025-11-08

How to determine if a string or array contains specific content in AnqiCMS?

In the daily work of content operation, we often need to make judgments and displays based on specific information of the content.For example, if a blog post mentions a hot keyword, we may want to give it a special tag; or if a product description includes a certain feature, we want to adjust its display style accordingly.The template engine of AnQiCMS provides a flexible and intuitive way to determine whether a string or array contains specific content, making dynamic content display and personalized processing very convenient.

2025-11-08

How to debug and view the complete structure and value of variables in the template?

When developing website templates in AnQi CMS, we often need to understand the specific structure of a variable on the page and what data it contains so that we can accurately call its properties.When dealing with complex business logic or unfamiliar template variables, being able to quickly view the complete structure and value of variables is undoubtedly the key to improving development efficiency.The Anqi CMS based on the Django template engine provides a concise and powerful variable debugging method for us.### Core Tool: `dump` Filter An enterprise CMS template provides a `dump` named

2025-11-08

How to display the comment form and submit comments in Anqi CMS?

It is crucial to establish an effective communication channel with visitors in website operation, and the message function is one of the key tools to achieve this goal.It can not only help websites collect user feedback and answer questions, but also promote user participation, enhance the interactivity and stickiness of the website.For users using AnQiCMS, the built-in message function provides a convenient and flexible solution, allowing you to easily display and submit message forms without writing complex code.### Overview of AnQi CMS Message Function The AnQi CMS message function is designed to be very user-friendly

2025-11-08

How to display the document comment list and implement pagination?

When using Anqi CMS to manage website content, the comment function on the document detail page is an important part of interacting with readers.Effectively display these comments and ensure that the page maintains good loading speed and user experience as the number of comments increases, it is necessary to properly handle the display and pagination of the comment list.The Anqi CMS provides very intuitive and powerful template tags, helping us easily achieve this goal.

2025-11-08