During the template creation process of AnQi CMS, we often encounter the need to concatenate a specific field from an array (or list) queried from the database with a symbol to form a continuous string for beautiful display on the page. For example, to connect multiple tags (Tag) of an article or to display all the characteristics of a product.

The template engine of Anqi CMS supports syntax similar to Django templates, which makes handling such needs intuitive and flexible.The core idea is to use the loop structure of the template engine to traverse the array and gradually construct the string we want during the traversal.

Understand the data structure in AnQi CMS template

In AnQi CMS, when we use likearchiveList/tagListsuch labels often return an array or slice containing multiple "items". Each "item" is typically a struct (object) that contains multiple fields (such asTitle/Link/Descriptionauto").For example,archiveListTags will return a list of document (archive) objects, each with its ownTitle/CreatedTimesuch properties.

To concatenate the value of a specific attribute in these objects into a string, we cannot directly perform the concatenation operation on the entire list of objects, but instead we need to extract the values of the attributes we are interested in one by one.

Core Method: Skillfully Using Loops and Concatenation

To achieve this goal, we can adopt a general template concatenation strategy, which combines loops, variable assignment, and string concatenation operations.

步骤一:Traverse array to get data

Firstly, we need a loop label (forLoop) to traverse the array obtained through the AnQi CMS tag. Assuming we start fromarchiveListauto obtained a set of documentsarchivesand we want to connect the titles of these documents:

{% archiveList archives with type="list" limit="5" %}
    {# 循环将在这里进行 #}
{% endarchiveList %}

Inside the loop,itemthe variable will represent each document object in the array in turn. We can access the title of each document via:item.Title.

Step two: Usesetand~Operator string concatenation

In order to build the final string, we need a variable to store the concatenation result. The Anqi CMS template engine allows us to use{% set 变量名 = 值 %}Tags can be used to define and modify variables. It also supports~symbols as string concatenation operators.

We can initialize an empty string variable before the loop starts and then append the required fields of each element to this variable inside the loop.

{% set joined_titles = "" %} {# 初始化一个空字符串变量 #}
{% archiveList archives with type="list" limit="5" %}
    {% for item in archives %}
        {# 在这里拼接标题 #}
    {% endfor %}
{% endarchiveList %}

Step three: Skillfully handle delimiters (usingforloop.last)

When concatenating strings, a common issue is how to add a separator between each element while avoiding an extra separator at the end. Fortunately, forThe loop provides a special variable insideforloop, which contains information about the current loop state, whereforloop.lastis a boolean value used to determine if it is the last element of the loop.

Utilizeforloop.lastWe can add a separator after each element, but skip it after the last one.

Combining all the above steps, a complete concatenation example may look like this:

{# 假设我们想将最近5篇文章的标题用逗号和空格连接起来 #}
{% set article_titles_str = "" %} {# 初始化一个空字符串变量来存储拼接结果 #}

{% archiveList archives with type="list" limit="5" %}
    {% for item in archives %}
        {% set article_titles_str = article_titles_str ~ item.Title %} {# 拼接当前文章标题 #}
        {% if not forloop.last %}
            {% set article_titles_str = article_titles_str ~ ", " %} {# 如果不是最后一个,添加分隔符 #}
        {% endif %}
    {% endfor %}
{% endarchiveList %}

<p>最近文章标题汇总:{{ article_titles_str }}</p>

This code will initialize firstarticle_titles_strIt is empty, then it will iteratearchivesEach item in the list. In each loop, it will take the currentitemofTitleProperty added toarticle_titles_strand then it will checkforloop.lastif the currentitemNot the last item in the list, a separator will be added after the title.,Finally,article_titles_strThe string will contain all titles connected by the specified separator.

More concise scenario: Directly use on string arrays|joinFilter

if your array is itself a simple string array (not an object array), or if you have already converted an object array to a string array in another way, then the Anqi CMS template engine provides a simpler|joinFilter.

For example, if you have a custom field that stores a comma-separated string, you can use|splitthe filter to convert it to an array of strings, then use|joinFilter connected with different delimiters.

{# 假设有一个字符串:"标签A,标签B,标签C" #}
{% set raw_tags_str = "Go语言,CMS建站,网站优化,模板设计" %}
{# 使用 |split 过滤器将其切割成字符串数组 #}
{% set tags_array = raw_tags_str|split:"," %}

{# 现在,tags_array 是一个字符串数组,我们可以直接使用 |join 过滤器连接它们 #}
<p>文章关联标签:{{ tags_array|join:" | " }}</p>
{# 输出: 文章关联标签:Go语言 | CMS建站 | 网站优化 | 模板设计 #}

Please note,|joinThe filter directly acts on a list (or slice) and concatenates each element of the list.If the elements in the list are not strings, they are usually automatically converted to strings before concatenation.archiveDirectly such complex structures as objects,{{ archives|join:", " }}It is not feasible because the template engine does not know which property of the objects you want to connect. Therefore, the method of concatenating the above loop for object arrays is still the preferred choice.

Actual application scenarios

  • Show article tags:getarchive.TagsList (assumedTags) is a string array), then|joinconnect.