In AnQiCMS template development, we often encounter situations where we need to display a series of related data, such as multiple tags for an article, various characteristics of a product, or multiple options stored in a custom field.These data are often present in templates in the form of arrays, and we hope to display them in a concise and beautiful string form, such as connecting them with commas, slashes, or other symbols.
AnQiCMS's template system is based on a syntax similar to Django, providing powerful and flexible filter functions. The core of achieving the requirement to display array elements linked into a string is to skillfully use built-injoinfilter.
Core function:joinFilter
joinThe filter, as the name implies, is used to concatenate each element of an array (or a collection that can be treated as an array) with a specified symbol, ultimately forming a complete string.This allows multiple data to be displayed on the web page in a more compact and readable manner.
Its basic syntax is very intuitive:
{{ 数组变量|join:"分隔符" }}
Among them,数组变量And it is the array you want to process, while"分隔符"Then it is the arbitrary string you want to use to connect array elements, such as a comma","/" / ", or any character you need.
Example: Directly connect a simple array
Assuming your template has a namedsystemFeaturesarray variable that contains some string elements, such as:["高性能", "模块化设计", "灵活权限"]If you want to display these features with Chinese commas, you can write it like this:
{% set systemFeatures = '["高性能", "模块化设计", "灵活权限"]'|list %}
<p>AnQiCMS 的核心优势包括:{{ systemFeatures|join:"," }}</p>
{# 显示结果:AnQiCMS 的核心优势包括:高性能,模块化设计,灵活权限 #}
We used herelistThe filter defines a string array directly in the template, and then throughjoin:","They were connected into a string.
Combined use:splitthe filter meetsjoinFilter
In actual operation, many times, the custom fields on the backend are stored in the form of a comma-separated string (or other symbols) for convenience of management or storage. For example, the keywords of an article may be stored as"Go语言,CMS系统,企业建站"In this case, we first need to convert this string into an array, and then concatenate it usingjoina filter. At this point,splitThe filter comes into play.
splitThe filter can split a string according to the separator you specify