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["你", "好"].