How to split a string into an array using a specific delimiter in Anqi CMS template?

Calendar 👁️ 65

In Anqi CMS template development, we often encounter scenarios where we need to process specific strings.For example, an article's keywords may be stored as a comma-separated string, and we want to display them as independent tags on the front end.At this point, splitting a string into an array with a specific delimiter becomes the key step in handling this kind of problem.

The AnQi CMS template engine supports syntax similar to Django, and it provides a rich set of filters to help us process data.Today, let's delve into how to easily split strings into arrays using these powerful filters in Anqi CMS templates.


Unlock the potential of data: Practical guide to splitting strings into arrays in Anqi CMS template

In website content display and data processing, converting a string containing a specific delimiter into an array is a very common requirement.Whether it is to display multiple tags of articles, product parameter lists, or handle multi-value data in custom fields, mastering this skill can make your templates more flexible.splitfilter.

splitFilter: The Core Tool for String Splitting

splitThe filter is a tool used to split strings according to the delimiter you specify and convert them into an iterable array (slice or list).This allows you to perform operations on each part of the string individually, such as looping through, conditional judgments, and so on.

Working principle:

When you apply a string tosplitWhen filtering, you need to provide a delimiter as the basis for division.The filter will find all positions of the separator in the string, and extract the content between the separators to form array elements.

Basic usage example:

Assuming you have a variablearticleTagsIts value is"SEO,内容运营,网站优化,用户体验". You want to display these tags separately.

  1. Define a string variable (if not directly from the data):

    {% set articleTags = "SEO,内容运营,网站优化,用户体验" %}
    
  2. UsesplitThe filter splits it into an array:

    {% set tagsArray = articleTags|split:"," %}
    

    Here, we use the English comma“,”as a separator.tagsArrayNow it is an array containing four elements:["SEO", "内容运营", "网站优化", "用户体验"].

  3. Loop through the array and display:Once a string is split into an array, you can usefora loop to iterate over this array and perform operations on each element.

    <div class="article-tags">
        {% for tag in tagsArray %}
            <span class="tag">{{ tag }}</span>
        {% endfor %}
    </div>
    

    This code will generate an HTML structure like this on the front end:

    <div class="article-tags">
        <span class="tag">SEO</span>
        <span class="tag">内容运营</span>
        <span class="tag">网站优化</span>
        <span class="tag">用户体验</span>
    </div>
    

Handle separators with spaces:

If your string delimiter contains spaces, for example"关键词A, 关键词B, 关键词C", you can in thesplitFilter directly specify a delimiter containing spaces:

{% set productFeatures = "颜色:红色, 尺寸:L, 材质:纯棉" %}
{% set featureList = productFeatures|split:", " %} {# 注意分隔符是", ",包含一个空格 #}

<ul class="product-features">
    {% for feature in featureList %}
        <li>{{ feature }}</li>
    {% endfor %}
</ul>

This will convertproductFeaturesSplit into["颜色:红色", "尺寸:L", "材质:纯棉"].

make_listSpecial scenario for splitting by characters in the filter:

exceptsplitIn addition to splitting by the specified delimiter in the filter, AnQi CMS also providesmake_listA filter that splits each character of a string (including Chinese characters) into an independent element of an array.This is very useful in some special cases, such as when it is necessary to handle each character of a string separately.

Usage example:

Suppose you have a mysterious code that needs to be displayed character by charactersecretCode = "A1你2".

{% set secretCode = "A1你2" %}
{% set charArray = secretCode|make_list %}

<div class="secret-code">
    {% for char in charArray %}
        <span class="char">{{ char }}</span>
    {% endfor %}
</div>

This code will generate:

<div class="secret-code">
    <span class="char">A</span>
    <span class="char">1</span>
    <span class="char">你</span>
    <span class="char">2</span>
</div>

Practical skills and precautions

  1. Data source:You usually get the strings to split from the following places in the template:

    • (Document details:archiveDetailCustom field of the):The field that defines a multi-value information containing for articles or product models in the background.
    • System settings (system)、Contact Information(contact) Custom parameters:Custom multi-value configuration stored.
    • Tags(tagList) or category (categoryDetailDescription or keyword field:It may also be separated by commas.
  2. Handle extra spaces:If the user enters data irregularly in the background, it may result in"SEO , 内容运营 , 网站优化"Such a string, where the delimiter has extra spaces on both sides.

    • Method one:EnsuresplitThe delimiter contains spaces, such assplit:", ".
    • Method two (more robust):If the delimiter is not fixed or the data is very chaotic, you can first usesplitsplit, then inforthe loop to use for each elementtrima filter to remove leading and trailing spaces:
      
      {% set messyTags = " SEO ,内容运营,  网站优化 " %}
      {% set rawTags = messyTags|split:"," %}
      <div class="article-tags">
          {% for tag in rawTags %}
              <span class="tag">{{ tag|trim }}</span> {# 对每个标签元素进行trim处理 #}
          {% endfor %}
      </div>
      
  3. empty strings or no delimiter cases:

    • If the string is empty("")splitThe filter will return an empty array,forin the loop{% empty %}the block will execute.
    • if the string does not contain the specified delimiter (such as"单一标签"usingsplit:","Splitting,...splitThe filter will return an array containing the original string as the only element:["单一标签"].forThe loop will still execute once normally.

Splitting a string into an array is a basic and powerful skill in the development of Anqi CMS templates. By using it flexibly,splitandmake_listcombined with filters,forLoop, you will be able to process and display website data more efficiently, providing users with richer and more structured content experiences.


Frequently Asked Questions (FAQ)

Q1: Why do my string split elements have unnecessary spaces? A1: This is usually because the delimiter before and after the original string contains spaces, for example"关键词1, 关键词2". When you usesplit:","When splitting, each element will become" 关键词1"and" 关键词2". The solution is to specify the delimiter in thesplitfilterer as", "(including spaces), or to use it in the loop to traverse each element whentrimfor example, a filter (such as{{ tag|trim }}Remove the leading and trailing spaces from each element to ensure the data is tidy.

Q2: After splitting, I get an array. How do I get a specific element from it? A2: Similar to most programming languages, you can access specific elements in an array by index. The index of an array usually starts from 0. For example, if you have already split a string intomyArrayIn a variable, you can{{ myArray[0] }}get the first element,{{ myArray[1] }}get the second element, and so on. But please note,

Related articles

How would AnQi CMS handle if the string format is incorrect when using the `list` filter to define an array?

In website content operation, we often need to display various list data in templates, such as a set of keywords, product features, or navigation links.AnQiCMS provides a powerful template engine, where the `list` filter is a very practical feature, allowing us to directly convert string-formatted data into an iterable array object in the template, greatly enhancing the flexibility of the template.

2025-11-08

How to iterate over an array defined in an AnQi CMS template using the `list` filter?

In Anqi CMS template design, we often encounter situations where we need to define and iterate over some fixed or small array data.Although most dynamic content is retrieved through built-in tags such as `archiveList`, `categoryList`, etc., it is more convenient to directly process arrays in the template for some localization configurations, custom options, or static lists.AnQi CMS provides the `list` filter, combined with the `for` loop tag, it can easily meet this requirement.

2025-11-08

Can 'list' filter be used to define an array that includes numeric types in the AnQi CMS template?

During the development of AnQi CMS templates, we often need to handle various data, among which arrays (or lists) are commonly used to organize data.When it comes to defining an array containing different data types directly in a template, many friends may be curious whether types like numbers can also be processed and included in the `list` filter?The answer is affirmative.The `list` filter in Anqi CMS template is designed to be very flexible, it fully supports including numeric data in the defined array.

2025-11-08

How to define a string array directly in the AnQi CMS template?

In AnQi CMS template development, we often encounter the need to display some list data on the page, such as navigation menus, category tags, or some fixed options.When this data is not suitable for dynamic retrieval from the backend database, or when we just need a simple and fixed set of strings, defining a string array directly in the template is very convenient and efficient.Our Anqi CMS provides a flexible way to handle such requirements based on the Django template engine syntax.

2025-11-08

How does the `split` filter split a string into an array of characters?

When using AnQiCMS for website content creation and template development, string processing is a common requirement.Sometimes, we need to split a complete string into smaller parts, such as breaking it down into an array of characters.This article will delve into the powerful `split` filter feature in AnQiCMS and provide practical examples.

2025-11-08

How to concatenate array elements in an Anqi CMS template with a custom character into a string?

In AnQi CMS template design, we often encounter situations where we need to display list-type data, such as multiple tags of an article, multiple image links on a product details page, or multiple options stored in a custom field.Directly outputting these array-shaped data to the page will often show a similar format like `["Label one", "Label two", "Label three"]`, which clearly does not meet the aesthetic and reading habits of users.At this point, we need to find a method to separate each element of the array with a custom character (such as a comma

2025-11-08

How does the `join` filter behave when processing non-array objects (such as strings)?

In Anqi CMS template development, the `join` filter is a very practical tool, mainly used to concatenate elements of an iterable object (such as an array or list) into a single string with a specified separator.However, when we apply the `join` filter to non-array objects, especially strings, its behavior may be different from what we initially imagine, but understanding its working principle can help us use it more flexibly.### The basic functionality of `join` filter review First, let's review the most common uses of the `join` filter

2025-11-08

How to extract elements within a specified range from an array or string in Anqi CMS template?

In AnQiCMS template development, we often need to finely control the displayed content, such as extracting part of the information from a long text, or displaying only the first few elements from a list.Fortunately, AnQiCMS uses a Django-like template engine that provides a very useful tool - the `slice` (slicing) filter, which can help us easily meet these needs.The `slice` filter is a very flexible feature that is not only applicable to string (text) but also to array (list) data

2025-11-08