In the powerful template system of Anqi CMS, flexible data handling is the key to building dynamic websites.Many times, the data we obtain from the backend, such as tags, keywords, or custom field values, may be stored in the form of a comma-separated string, but we want to handle them as separate items in the frontend template.listandsplitThe filter is particularly important, as it helps us convert strings into arrays, thus enabling more refined control and display in the template.

Why do we need to convert a string to an array?

Imagine that you have set multiple tags for a product article, which may be saved asIn the template, you may want to display these tags separately, even generate an independent link or style for each tag.If the data is still a single string, it will be difficult to achieve this.["手机", "智能", "通讯"]With such an array, we can easily traverse these elements and achieve various dynamic display effects.

The template engine of AnQi CMS supports Django-style syntax and provides a rich set of filters to handle such data transformation needs. Among them,splitandlist就是将字符串变为数组的利器。

splitFilter: Split the string into an array

splitThe filter, as the name implies, is to split a string into multiple independent strings based on the specified delimiter, and then combine them into an array.This is very useful for handling multi-value fields stored with specific delimiters (such as commas, spaces, pipes, etc.).

Usage:

In the template, you can use it like this:splitFilter:

{% set rawString = "安企CMS,内容管理,模板定制,GoLang" %}
{% set stringArray = rawString | split:"," %}

Here,rawString是你要处理的原始字符串变量,split:","表示以逗号作为分隔符进行切割。执行后,stringArray就会变成一个包含["安企CMS", "内容管理", "模板定制", "GoLang"]using a comma as a delimiter.

Example: Handling article tags

Assuming your article objectarchiveThere is aTagsField, the value of which is"SEO优化,网站建设,用户体验". You can display these tags in the template like this:

{% set articleTags = archive.Tags | split:"," %}
<div class="article-tags">
    {% for tag in articleTags %}
        <span class="tag-item">{{ tag | trim }}</span>
    {% endfor %}
</div>

In this example,trimThe filter is also used to remove any leading and trailing spaces, ensuring that each tag is clean and tidy.

Caution:

  • Delimiter flexibility:The delimiter can be any string, for example, if you use “|” to separate, writesplit:" | ".
  • The delimiter does not exist:If the string does not contain the specified delimiter,splitThe filter will return an array containing only the original strings.
  • Empty delimiter:If you set the delimiter to an empty stringsplit:""so thatsplitThe filter will split each character of the original string (including Chinese characters) into an element of the array.

listFilter: Construct arrays directly in the template

WithsplitFilters emphasize the 'cutting' of existing strings differently,listThe filter provides a more direct, more structured way to construct an array in templates.It accepts a string formatted like a JSON array and parses it into an actual array object.This is very convenient when it is necessary to define a set of fixed options or to perform some preset value processing.

Usage:

listThe filter accepts a string enclosed in double quotes that is in JSON array format:

{% set allowedRoles = '["管理员", "编辑", "访客"]' | list %}

Here,allowedRolesand is parsed into a JSON array containing["管理员", "编辑", "访客"]using a comma as a delimiter.

Example: Display different content based on the role

If you want to display different operation options on the page based on the current user's role, you can first define a list of allowed operation roles:

{% set editorActions = '["发布", "修改", "删除"]' | list %}
{% set currentUserRole = "编辑" %} {# 假设这是从某个地方获取的当前用户角色 #}

<ul class="actions-list">
    {% for action in editorActions %}
        {% if currentUserRole == "编辑" %} {# 示例,更复杂的判断逻辑可在此处展开 #}
            <li>
                <a href="/{{ action }}">{{ action }}操作</a>
            </li>
        {% endif %}
    {% endfor %}
</ul>

listFilter is suitable when you need to hardcode some array in the template or when the string obtained from some variable strictly adheres to JSON array format.

How to handle arrays in templates?

Once throughsplitorlistThe filter successfully converts a string to an array, allowing you to use the powerful loop function of the AnQi CMS template engine to handle these arrays.

UseforLoop through the array:

The most common method is to useforLoop Label:

{% for item in yourArray %}
    {# 在这里处理每个数组元素 #}
    <span>{{ item }}</span>
{% empty %} {# 可选:如果数组为空则执行此部分 #}
    <p>没有可显示的项目。</p>
{% endfor %}

Inside the loop,itemThe variable will represent each element in the array sequentially, you can display it, make conditional judgments, or combine it with other filters for further processing.

Recombine array elements:joinFilter

It is interesting that after processing the array, if you need to recombine the array elements into a string again (for example, to display in a compact text paragraph),joinFilter just fits the occasion. It workssplitexactly the opposite.

{% set processedTags = ["安企CMS", "模板定制", "实用技巧"] %}
<p>相关主题:{{ processedTags | join:" | " }}</p>
{# 输出:相关主题:安企CMS | 模板定制 | 实用技巧 #}

Additional tip:make_listFilter

If you need to split a string into an array of individual characters, for example, to handle Chinese character strings or character games,make_listThe filter will be more convenient. It will treat each character (including spaces, punctuation, and Chinese characters) in the string as an independent element of an array.

{% set chineseString = "你好安企" %}
{% set charArray = chineseString | make_list %}
{# charArray 将会是 ["你", "好", "安", "企"] #}

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

Summary

MastersplitandlistFilter, is a practical skill in the development of AnQi CMS templates.splitFilters allow you to easily parse the multi-value strings stored in the background,listThe filter provides a convenient way to define arrays directly in the template. Combinedforloop andjoinFilter, you will be able to control and display various dynamic contents on the website more flexibly, thereby providing users with a richer and more personalized browsing experience.


Common Questions (FAQ)

1.splitandmake_listWhat are the main differences between the filters?

splitThe filter is based on the 'delimiter' you specify to split the string into an array of substrings. For example,"A,B,C" | split:","You will get["A", "B", "C"].