In the powerful template system of Anqi CMS, flexible data processing is the key to building dynamic websites.Most of the time, the data we retrieve from the background, such as tags, keywords, or custom field values, may be stored in the form of comma-separated strings, but we want to treat them as separate items in the frontend template.This is provided by Anqi CMSlistandsplitFilters are particularly important, as they help us convert strings into arrays, allowing for more refined control and display in templates.
Why do we need to convert a string to an array?
Imagine, you have set multiple tags for a product article, which may be saved as "mobile, smart, communication" in the background.In the template, you may want to display these tags separately, even to generate an independent link or style for each tag.If the data is still a single string, it will be difficult to implement.By converting 'phone, smart, communication' to["手机", "智能", "通讯"]With such an array, we can easily iterate over these elements and achieve various dynamic display effects.
The AnQi CMS template engine supports Django-style syntax and provides rich filters to handle such data transformation needs. Among them,splitandlistIt is a powerful tool to convert strings into arrays.
splitFilter: Split a string into an array.
splitThe filter, as the name implies, is to split a string into multiple independent strings according to the separator you specify, and then combine them into an array.This is very useful for handling multi-value fields stored in the background with specific delimiters (such as commas, spaces, pipes, etc.)
Usage:
In the template, you can use it like thissplitFilter:
{% set rawString = "安企CMS,内容管理,模板定制,GoLang" %}
{% set stringArray = rawString | split:"," %}
here,rawStringIt is the original string variable you need to handle,split:","indicating that it is split by commas. After execution,stringArrayIt will become an array containing["安企CMS", "内容管理", "模板定制", "GoLang"]array.
Example: Processing article tags
Assuming your article objectarchiveHas aTagsField, its value is"SEO优化,网站建设,用户体验". You can display these tags like this in the template:
{% 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 or trailing spaces, ensuring that each tag is clean and tidy.
Note:
- Delimiter flexibility:The delimiter can be any string, for example, if you use “|” to separate, write
split:" | ". - The separator does not exist:If the string does not contain the specified delimiter,
splitThe filter will return an array that contains only the original string. - Empty separators:If you set the delimiter to an empty string
split:""thensplitThe filter will split each character of the original string (including Chinese) into an element of the array.
listFilter: Construct the array directly in the template
withsplitThe filter focuses on 'cutting' the existing string differently,listA filter provides a more direct, structured way to construct an array in the template.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 a JSON array format:
{% set allowedRoles = '["管理员", "编辑", "访客"]' | list %}
here,allowedRolesIt will be parsed into a containing["管理员", "编辑", "访客"]array.
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 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>
listThe filter is suitable when you need to hardcode some arrays in the template or when the strings obtained from a variable strictly comply with the JSON array format.
How to handle arrays in the template?
Once throughsplitorlistThe filter successfully converts a string to an array, and then you can use the powerful loop function of the Anqi CMS template engine to handle these arrays.
UseforLoop through the array:
The most common way is to useforLoop label:
{% for item in yourArray %}
{# 在这里处理每个数组元素 #}
<span>{{ item }}</span>
{% empty %} {# 可选:如果数组为空则执行此部分 #}
<p>没有可显示的项目。</p>
{% endfor %}
Inside the loop,itemVariables will represent each element in the array sequentially, you can display them, make conditional judgments, or combine them with other filters for further processing.
Recombine array elements: joinFilter
It's interesting that after you have processed the array, you might need to recombine the array elements into a string (for example, to display in a compact text paragraph),joinThe filter is just what it should be. It issplitthe exact opposite in function.
{% set processedTags = ["安企CMS", "模板定制", "实用技巧"] %}
<p>相关主题:{{ processedTags | join:" | " }}</p>
{# 输出:相关主题:安企CMS | 模板定制 | 实用技巧 #}
Additional hint:make_listFilter
If you need to split a string into an array of individual characters, for example, when dealing with Chinese character strings or character games,make_listThe filter will be more convenient. It will treat every character (including spaces, punctuation, and Chinese characters) 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
MastersplitandlistA filter is a practical skill in the development of Anqi CMS templates.splitA filter allows you to easily parse the multi-value strings stored in the background, andlistThe filter provides a convenient way to define an array directly in the template. Combinedforloop andjoinThe filter allows you to more flexibly control and display various dynamic contents on the website, thereby providing users with a richer and more personalized browsing experience.
Frequently Asked Questions (FAQ)
1.splitandmake_listWhat are the main differences of the filter?
splitThe filter is based on the separator you specify to split the string into an array of substrings. For example,"A,B,C" | split:","You will get["A", "B", "C"]. While `make