How to concatenate array elements obtained by traversing AnQiCMS templates with a specified separator into a string?

Calendar 👁️ 71

During the template creation process of Anqi CMS, we often encounter the need to concatenate a field from an array (or list) queried from the database with a specific symbol to form a continuous string, for the purpose of displaying it beautifully on the page, such as connecting multiple tags (Tag) of an article or displaying all the features of a product.

The template engine of AnQi CMS supports syntax similar to Django templates, making it intuitive and flexible to handle such requirements.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 of Anqi CMS template

In Anqi CMS, when we use things likearchiveList/tagListWhen such tags are used, they often return an array or slice containing multiple "items". Each item is typically a structure (object) that contains multiple fields such asTitle/Link/Descriptionsuch asarchiveListtags will return a list of document (archive) objects, each with its ownTitle/CreatedTimesuch properties.

We cannot directly concatenate the values of a specific property of these objects into a string, but we need to extract the values of the properties we are interested in one by one.

Core method: skillfully use loops and concatenation

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

Step one: Traverse the array to get data

Firstly, we need a loop tag (forloop) to traverse the array obtained through the AnQi CMS tag. Assuming we start fromarchiveListObtained a set of documentsarchivesAnd we want to concatenate 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. We can accessitem.Titlethe title of each document.

Step two: usesetand~String concatenation with operators

To build the final string, we need a variable to store the concatenated result. The Anqi CMS template engine allows us to use{% set 变量名 = 值 %}Label to define and modify variables. It also supports~operator as a string concatenation operator.

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

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

Step three: Skillfully handle separators (usingforloop.last)

When concatenating strings, a common problem is how to add a separator between each element while avoiding an extra separator at the end. Fortunately,forA loop provides a special variable insideforloopwhich contains the current loop state information, includingforloop.lastIt is a boolean value used to determine whether the current element is the last one in the loop.

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

Combining 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 first initializearticle_titles_strempty, then iteratearchiveseach item in the list. In each iteration, it will take the currentitemofTitlethe attribute toarticle_titles_strin. Then, it will checkforloop.last, if the currentitemIf it is not the last item in the list, a separator will be added after the title.,Finally,article_titles_strIt will contain the string connected by the specified separator of all titles.

The scenario: Use the string array directly|joinFilter

If your array is itself a simple string array (not an object array) or you have already converted an object array into a string array in some other way, then the Anq CMS template engine provides a more concise|joinfilter.

For example, if you have a custom field that stores a comma-separated string, you can use|splitthe filter to convert it into an array of strings, then use|joinFilter connected by 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 operates directly 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 being concatenated.But for likearchiveComplex structures like objects, directly.{{ archives|join:", " }}It is not feasible because the template engine does not know which attribute of the objects you want to connect. Therefore, the method of looping concatenation mentioned above is still the preferred choice.

Application scenarios in practice

  • Display article tags:Obtainarchive.TagsList (assumingTagsis a string array), then|joinconcatenate. If

Related articles

How to quickly split a comma-separated string into an array for traversal in AnQiCMS template?

In website content operation, we often encounter such situations: a content field stores a series of interconnected information, usually connected by commas.For example, an article may be associated with multiple tags ("SEO, website optimization, content marketing"), a product may have various color options ("red, blue, green"), or you may need to display a set of user-defined keywords.How to efficiently convert the comma-separated strings to traversable data structures when we need to display them one by one on the front-end page or perform more complex processing

2025-11-07

Why does the AnQiCMS template default to escaping HTML code? How can HTML content be safely output?

When using AnQiCMS for template development, we may notice an interesting phenomenon: sometimes, the HTML code directly output in the template, such as a `<div>` tag, is not parsed by the browser into a visible area as expected, but is displayed exactly as it is, showing `&lt;div &gt; `such characters. This may be confusing, why does AnQiCMS default to escaping HTML code?How can we safely output the HTML content we want?--- ### One

2025-11-07

How to control the truncation length of the hyperlink text when using the AnQiCMS `urlizetrunc` filter?

In website content operation, we often need to display various hyperlinks in articles, comments, or list pages.These links may be pointing to other content within the site, external resources, or the contact email of the user.However, some excessively long links may not only destroy the page layout, affect the aesthetics, but may also reduce the user's reading experience.Especially in limited display space, long URLs can make content look disorganized.

2025-11-07

How does AnQiCMS automatically identify URLs or email addresses in text and convert them into clickable hyperlinks?

In the daily operation of websites, we often need to add various links in article content, such as URLs pointing to external resources, or email addresses for easy reader contact.Manually adding hyperlinks one by one is not only inefficient but also prone to errors.Fortunately, AnQiCMS provides very practical features that can intelligently identify URLs and email addresses in text and automatically convert them into clickable hyperlinks, greatly enhancing the efficiency and user experience of content editing.

2025-11-07

How to determine if a number (such as article ID) can be evenly divided by a specific number in the AnQiCMS template?

In website content display, we often encounter some special requirements, such as wanting to apply different styles to specific elements in the list, or to make some distinctions based on the parity of the article ID.AnQiCMS is a powerful template engine, drawing inspiration from the excellent design of Django templates, and provides a simple and efficient way to handle these logic.Today, let's discuss a very practical feature in the template: how to determine if a certain number (such as the article ID) can be evenly divided by a specific number.

2025-11-07

How to concatenate or add two strings or numbers in AnQiCMS template?

In AnQi CMS template design, dynamically combining text information or performing calculations on numerical values is a common requirement.It is crucial to be able to handle string concatenation and numeric addition operations flexibly, whether it is to build personalized product descriptions or to display dynamic data on the page.The Anqi CMS template system, drawing on the syntax of the Django template engine, provides a variety of intuitive and powerful methods to complete these tasks.

2025-11-07

How to implement the `replace` filter of AnQiCMS for batch replacement of sensitive words in article content?

In the field of content management, the flexibility and maintainability of website content are crucial.Batch replacement of article content is an efficient and practical operation, whether it is for brand unification, information update, or sensitive word filtering.AnQiCMS as a rich-featured enterprise-level content management system, provides a variety of content processing mechanisms, among which the `replace` filter and the background content batch replacement feature play a key role in different scenarios.

2025-11-07

How to automatically render the multi-line text (including newline characters) of AnQiCMS custom fields into HTML tags `<p>` and `<br/>`?

When using AnQiCMS to manage website content, we often take advantage of its powerful custom field features to enrich page information.Especially for text that needs to include multiline descriptions, notes, or detailed explanations, the 'Multiline Text' type in custom fields is undoubtedly the ideal choice.However, when we eagerly display these text contents with line breaks on the front-end page, we may find that the original line breaks are not automatically recognized by the browser, resulting in all the text being cramped together, greatly reducing the reading experience.This is actually a feature of HTML rendering mechanism

2025-11-07