The template system of AnQiCMS is favored by a wide range of content operators for its powerful flexibility and ease of use. It includes,splitFilter is a very practical feature, which helps us split a string into an array (or slice in Go language) according to a specified delimiter.However, when we wish to pass a specific part of this array as a parameter to other template tags or filters, we may feel somewhat confused.Don't worry, this article will discuss several efficient and commonly used methods to solve this problem in detail.
UnderstandingsplitThe basic function of the filter.
First, let's briefly review.splitThe function of the filter.It receives a string and a delimiter, then returns an array containing the sliced substrings.splitConvert it into["1001", "1002", "1003"]Such an array.
Its basic usage is:{% set my_string = "apple,banana,orange" %}
{% set fruit_array = my_string|split(",") %}At this time,fruit_arrayIt becomes an array containing three elements.
The core challenge lies in that AnQiCMS template tags and filters usually expect a single value (such as a string, number, or boolean) as an argument, rather than directly taking elements from the array output of the filter.my_string|split(",")[0]Passed to some tags, may not work as expected or the readability of the code is poor.
Solution one: utilizesetAssign tags, then pass elements
The most direct and recommended way is to firstsplitThe result of the filter processing is assigned to a temporary variable, and then the required elements are extracted from this variable as parameters to be passed.This enhances the readability of the code and makes subsequent operations more flexible.
Use
setCreate variables with tags:setTags allow you to define and assign variables in the template. You cansplitStore the output of the filter directly into this variable.{% set tag_ids_string = "10,25,30" %} {% set id_list = tag_ids_string|split(",") %}Now,
id_listIt is just a["10", "25", "30"]using a comma as a delimiter.Access array elements by index and pass parameters:Once you have
id_listVariables, you can access each element of the array by its index (starting from 0) and pass it as a parameter to other tags or filters.Suppose you want to get the element with ID of
10The document details:{% set tag_ids_string = "10,25,30" %} {% set id_list = tag_ids_string|split(",") %} {# 获取数组中的第一个元素("10")作为 archiveDetail 的 id 参数 #} {% archiveDetail first_doc with name="Title" id=id_list[0] %} <p>第一篇文档标题: {{ first_doc }}</p> {# 获取数组中的第二个元素("25")作为 archiveDetail 的 id 参数 #} {% archiveDetail second_doc with name="Title" id=id_list[1] %} <p>第二篇文档标题: {{ second_doc }}</p>This method is clear and straightforward, allowing you to precisely control every parameter passed to other tags.
Solution two: combined withforlooping, processing each element one by one
If your requirement is to iteratespliteach element that comes out, and perform the same operation on each element (for example, dynamically generate a content list based on each ID), then combineforLoops are a more elegant choice.
to
splitAssign the result to the loop variable:You can directly inputsplitThe result of the filter is used forforLoop iteration.{% set category_id_string = "1,5,8" %} {% set category_id_array = category_id_string|split(",") %} <h3>根据不同分类ID展示文档列表:</h3> {% for category_id in category_id_array %} <h4>分类ID: {{ category_id }} 的相关文档:</h4> {% archiveList archives_by_category with type="list" categoryId=category_id limit="3" %} <ul> {% for item in archives_by_category %} <li><a href="{{ item.Link }}">{{ item.Title }}</a></li> {% empty %} <li>该分类下没有文档。</li> {% endfor %} </ul> {% endarchiveList %} {% endfor %}In this example,
category_idIt will be in every loop iteration.category_id_arrayThe element of a list, which can be used directly asarchiveListTagscategoryIdparameters.
Advanced application: UsesplitRecombine the results or pass them to parameters that support lists
Some template tags or filters may expect a string connected by a specific delimiter (such as a comma), rather than an array directly. In this case, you can combinesplitandjoinFilter.joinThe filter can concatenate array elements into a string.
splitafterjoin:假设你有一个字符串 “apple,banana,orange”,但你只想提取其中的 “banana” 和 “orange”,然后将它们作为逗号分隔的参数传递给另一个标签,该标签期望一个逗号分隔的字符串作为EnglishcategoryIds.{% set fruit_string = "apple,banana,orange" %} {% set fruit_array = fruit_string|split(",") %} {# 假设你只想要 "banana" 和 "orange" 这两个,创建一个新数组或直接操作 #} {% set selected_fruits = fruit_array|slice:"1:" %} {# 从索引1开始截取 #} {# 将新数组重新连接成逗号分隔的字符串 #} {% set category_ids_param = selected_fruits|join(",") %} <p>选择的水果作为参数: {{ category_ids_param }}</p> {# 假设 archiveList 接受 categoryId="id1,id2" 这样的字符串 #} {% archiveList fruit_docs with type="list" categoryId=category_ids_param limit="5" %} <ul> {% for doc in fruit_docs %} <li>{{ doc.Title }}</li> {% endfor %} </ul> {% endarchiveList %}Here,
selected_fruits|join(",")auto translation: Will generate "banana,orange", then pass it tocategoryIdParameter.
Practical Suggestions
- clearly naming variables: Use
setWhen creating a temporary variable for a label, choose a meaningful name, which will greatly improve the readability and maintainability of the template. - Handle null values or out-of-bounds:When accessing array elements (
id_list[0]Before, it is better to useifCheck if the array exists or if the element is out of bounds with the tag, to avoid potential template rendering errors. For example:{% if id_list and id_list|length > 0 %} {# 安全地访问 id_list[0] #} {% endif %} - Understand the type of tag parameters:Before passing parameters, make sure you understand the expected parameter type of the target template tag or filter (whether it is a single string, number, or comma-separated string, etc.).
The strength of AnQiCMS template system lies in its flexible combination usage. By masteringsplit/set/forandjoinEnglish labels and filters allow you to build more dynamic and intelligent template content, better meeting the operation needs of the website.
Common Questions (FAQ)
Q:
splitCan the array elements cut out by the filter be directly passed to parameters that require comma-separated strings?Answer: No.splitThe filter produces an array as the result, while many tag parameters expect a single string value (even if the string contains comma-separated data). You need to usejoinThe filter reconnects the array into a comma-separated string and then passes it to these parameters. For example:my_array|join(",").Question: If
splitThe resulting array is empty, and if accessed directlymy_array[0]will it cause an error?答:AnQiCMS 的模板引擎通常会比较健壮,当数组为空或索引越界时,直接访问 Englishmy_array[0]usually will not cause template rendering errors, but will return an empty value (such as an empty string ornilThis may cause labels that depend on this value to fail to function properly. To ensure the stability of the template, it is recommended to perform a check before accessing array elements, for example{% if my_array and my_array|length > 0 %}{{ my_array[0] }}{% endif %}.**Question:**
splitFilter supports which delimiters? If I need