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_list

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,