The template system of AnQiCMS (AnQiCMS) is favored by content operators for its powerful flexibility and ease of use. Among them,splitThe filter is a very practical feature that helps us split a string into an array (or slice in Go language) according to a specified delimiter.However, when we want to pass a specific part of this array as a parameter to other template tags or filters, we may feel some confusion.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 takes a string and a delimiter, then returns an array containing the sliced substrings.For example, if you have a string containing multiple IDs, such as '1001,1002,1003', you can usesplitConvert it to["1001", "1002", "1003"]such an array.
The basic usage is:{% set my_string = "apple,banana,orange" %}
{% set fruit_array = my_string|split(",") %}at this point,fruit_arrayIt becomes an array containing three elements.
The core challenge lies in that AnQiCMS template tags and filters usually expect to receive a single value (such as a string, number, boolean) as a parameter, rather than directly taking elements from the array output of the filter. Directly takingmy_string|split(",")[0]Passed to some tags may not work as expected, or the readability of the code may be poor.
Solution one: utilizesetAssign tags and then pass elements
The most direct and recommended way is to firstsplitThe result of the filter is assigned to a temporary variable, and then the required elements are taken from this variable as parameters for transmission.This enhances the readability of the code and makes subsequent operations more flexible.
Use
setCreate a variable using tags:setTags allow you to define and assign variables in the template. You can directlysplitStore 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"]array.Access array elements by index and pass parameters:Once had
id_listA variable, 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 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 concise, allowing you to precisely control each parameter passed to other tags.
Solution two: combineforLoop, process elements one by one
If your requirement is to traversespliteach 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
splitThe result is assigned to the loop variable:You can directly putsplitThe result of the filter is usedforthe iteration of the loop.{% 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 each loop iteration.category_id_arrayA direct element, which can be used asarchiveListlabel'scategoryIdto use the parameter.
Advanced application: tosplitRecombine 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 a direct array. In this case, you can combinesplitandjoinfilter.joinThe filter can concatenate array elements into a string.
splitafterjoin:Assuming you have a string "apple,banana,orange", but you only want to extract "banana" and "orange", and then pass them as comma-separated parameters to another tag, which expects a comma-separated string ascategoryIds.{% 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(",")Generate "banana,orange" and then pass it tocategoryIdParameter.
Practical suggestions
- Name the variable clearly:Use
setWhen creating a temporary variable, 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 (such as
id_list[0]Use it beforeifCheck if the array exists or if the element is out of bounds to avoid potential template rendering errors. For example:{% if id_list and id_list|length > 0 %} {# 安全地访问 id_list[0] #} {% endif %} - Understand the tag parameter types:Before passing parameters, make sure you understand the parameter type expected by the target template tag or filter (whether it is a single string, number, or comma-separated string, etc.).
The strength of the AnQiCMS template system lies in its flexible combination usage. By proficiently usingsplit/set/forandjoinTags and filters, you will be able to build more dynamic and intelligent template content, better meeting the operation needs of the website.
Frequently Asked Questions (FAQ)
Question:
splitCan the array elements cut out by the filter be directly passed to parameters that require comma-separated strings?Answer: No.splitThe filter splits the result into an array, while many tag parameters expect a single string value (even if the string contains comma-separated data). You need to usejoinThe filter joins 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 you accessmy_array[0]it will cause an error?Answer: AnQiCMS's template engine is usually robust, when the array is empty or the index is out of bounds, it accesses directlymy_array[0]It usually does not cause a template rendering error, but it returns an empty value (such as an empty string ornilThis may cause the label that depends on this value to fail to work. To ensure the stability of the template, it is recommended to judge before accessing array elements, such as{% if my_array and my_array|length > 0 %}{{ my_array[0] }}{% endif %}.**Question:**
splitWhat delimiters does the filter support? If I need