How to extract and concatenate a specific field (such as Category ID) from a document list obtained through the `archiveList` tag?

Calendar 👁️ 68

When using AnQiCMS for website content management, we often need to extract specific information from the document list and combine it in a certain format, such as concatenating a series of document category IDs into a string for frontend dynamic rendering, SEO optimization, or specific data statistics.Although AnQiCMS's template system provides powerful data acquisition capabilities, it requires us to skillfully use its built-in tags and filters to directly implement this 'extract-combine' logic in the template.

Core Challenge: Extract and concatenate specific fields from the list data

The AnQiCMS template engine is designed for simplicity and efficiency, it allows us to retrieve data through tags and iterate through lists using a for loop.However, it is difficult to directly declare an empty array in a programming language, then add elements in a loop, and finally use a 'join' function to concatenate it in most template engines.We need a workaround within the scope of the template logic.

Use AnQiCMS template tags:archiveListwithforLoop

First, to get the document list, we will use AnQiCMS'sarchiveListThe label can return a collection of document objects based on the conditions we set, such as module ID, category ID, sorting method, etc.

Assuming we want to get all documents under a certain category and extract their category ID. TypicalarchiveListUsage is as follows:

{% archiveList archives with type="list" categoryId="1" limit="10" %}
    {# 此处将遍历返回的文档列表 #}
{% endarchiveList %}

here,archivesThe variable will contain a list of document objects. Next, we need to iterate over this list and access the specific fields of each document object. AnQiCMS template engine supportsforLoop to complete this task:

{% for item in archives %}
    {# 这里的 item 代表列表中的每一个文档对象 #}
    {# 我们可以通过 item.FieldName 的形式访问其属性,例如 item.CategoryId #}
{% endfor %}

Combine cleverlysetwith the tag andaddFilter to implement string concatenation

Now, we have been able to obtain the classification ID of each document.How to connect these individual ID values into a string, for example, AnQiCMS template providessetTags are used to declare and assign variables, as well asaddThe filter is used for concatenating strings or numbers, which is exactly the tool we use to achieve our goal.

Our approach is:

  1. First, usesetInitialize an empty string variable to store the final concatenated result.
  2. InforIn the loop, in each iteration, concatenate the current document's category ID to this string variable.
  3. In order to avoid extra delimiters at the beginning of a string (such as a comma), we can judge in the loop whether it is the first element, and do not add a prefix delimiter to the first element.

Here is the specific implementation code:

{# 步骤1:初始化一个空字符串变量来存储所有分类ID #}
{% set allCategoryIds = "" %}

{% archiveList archives with type="list" categoryId="1" limit="5" %} {# 假设获取分类ID为1的最新5篇文档 #}
    {% for item in archives %}
        {# 步骤2:在循环中,将当前文档的分类ID拼接到 allCategoryIds 变量中 #}
        {# 步骤3:判断是否是第一个元素,以控制分隔符的添加 #}
        {% if forloop.First %}
            {# 如果是第一个元素,直接拼接分类ID,不加逗号 #}
            {% set allCategoryIds = allCategoryIds|add:item.CategoryId %}
        {% else %}
            {# 如果不是第一个元素,先拼接逗号,再拼接分类ID #}
            {% set allCategoryIds = allCategoryIds|add:","|add:item.CategoryId %}
        {% endif %}
    {% endfor %}
{% endarchiveList %}

{# 循环结束后,allCategoryIds 变量就包含了所有分类ID组成的字符串 #}
<p>所选文档的分类ID集合:{{ allCategoryIds }}</p>

Code analysis:

  • {% set allCategoryIds = "" %}: We defined a variable namedallCategoryIdsand initialized it as an empty string.
  • {% for item in archives %}: TraversearchiveListThe list of documents obtained.
  • {% if forloop.First %}This is a very useful built-in variable in the AnQiCMS template loop, which determines whether the current iterating element is the first in the list.
  • {% set allCategoryIds = allCategoryIds|add:item.CategoryId %}:
    • item.CategoryId: Get the current document's category ID.
    • |add:value: This is the AnQiCMS template.addA filter. Its function is to concatenate the values on the left with the values on the right (if both are strings) or add them (if both are numbers). Here, it will concatenateallCategoryIds(string) withitem.CategoryId(Numbers, which will be implicitly converted to strings) concatenated.
  • {% else %}{% set allCategoryIds = allCategoryIds|add:","|add:item.CategoryId %}: If it is not the first element, we use|add:","concatenate a comma and then concatenate the current category ID.

In this way, we ultimately getallCategoryIdsThe variable will be a comma-separated string of category IDs, for example: 1,5,3,2,4.

Cautionary notes and **practice

  • Consideration of data volume:This method of dynamically concatenating strings in templates is efficient and practical for small to medium-sized data lists (such as tens to hundreds of items).If the document list is very large, such as tens of thousands of items, then performing a large number of string concatenations at the template layer may slightly increase the server's rendering burden.For extreme cases, consider preprocessing data in the AnQiCMS backend plugin or custom module and directly passing the concatenated string to the template.
  • Field type:Make sure you extract the field (such asitem.CategoryId) Can be implicitly converted to a string or it is already a string type. Numeric types are usually automatically converted, and other complex objects may require further processing.
  • Custom delimiter:You can change the code according to your needs in,Other delimiters such as|(space) and others.
  • Universality:This method is not only suitable for extracting category ID, but also for extracting document ID (item.Id) document title (item.Title) or any other field that can beitem.FieldNameaccessed.

Summary

AnQiCMS template system is limited in complex logic processing, but can be combined cleverlyarchiveListTag data acquisition,forLoop traversal,setTag assignment andaddThe filter's concatenation feature allows us to flexibly extract specific fields from a document list and combine them into the required string.This is very helpful for implementing various dynamic content display and data processing requirements, and also reflects the strong customizability of AnQiCMS in the field of content management.


Frequently Asked Questions (FAQ)

1. Why can't it be done directly inarchiveListUse a syntax similar to SQLGROUP_CONCATto concatenate strings?

AnQiCMS's template system is mainly used for data display and rendering, rather than complex data aggregation operations at the database level.archiveListThe purpose of the tag is to obtain the document list object, and like

Related articles

How does the `join` filter handle an empty array or an array with only one element in the AnQiCMS template?

In Anqi CMS template development, the `join` filter is a very practical tool that can concatenate multiple elements of an array (or list) with a specified delimiter to form a continuous string.This is very convenient when it comes to dynamically generating paths, tag lists, or any comma-separated values.In most cases, when we have an array containing multiple elements and use the `join` filter, its behavior is as expected.For example, if we have an array named `fruit_list` that contains `["apple",}

2025-11-08

When using the `join` filter, besides commas, what characters does AnQiCMS support as delimiters for joining array elements?

When developing with AnQiCMS templates, we often need to combine multiple elements in an array into a single string for display, whether it is for building navigation, displaying keywords, or formatting data lists.At this point, the `join` filter has become our helpful assistant.Many users may only be familiar with using commas (`,`) as separators, but in fact, AnQiCMS's `join` filter offers a wider range of choices, and its capabilities are far more than this.###

2025-11-08

How to connect multiple tags (Tag) in AnQiCMS template into a comma-separated keyword string?

In website operation, article tags (Tag) not only help in categorizing and retrieving content, but also enhance the page's SEO effect through keywords.Many times, we need to display multiple tags separated by commas at specific locations on the page, such as within the `<meta name="keywords">` tag or at the bottom of the article content."}AnQiCMS (AnQiCMS) provides a concise and flexible template syntax, making this operation very direct.### Understand the source of article tag data In AnQi CMS

2025-11-08

How to ensure that a number converted to `float` or `integer` is correctly identified as `true`/`false` in an `if` condition?

When using AnQiCMS for website content management, we often encounter scenarios where we need to make judgments and process data.Especially when data comes from user input or external interfaces and the type is uncertain, how to correctly identify the number converted through `float` or `integer` filters in the `if` condition judgment in the template is the key to ensuring logical accuracy. The AnQiCMS built-in template engine is powerful, supporting `float` and `integer` type conversions in GoLang.Understand the behavior of these transformation filters in different situations

2025-11-08

In AnQiCMS template, how to reassemble a string array split by `split` filter using the `join` filter into a custom formatted string?

In AnQiCMS template development, handling string data is one of the daily tasks.Sometimes, the strings we retrieve from the database may contain multiple values separated by a specific character, such as multiple keywords in an article, which may be stored in the form of In order to flexibly display this data on the front-end page, for example, to turn each keyword into a clickable tag or display it with different delimiters, we need to use the powerful string processing filters - `split` and `join` in the AnQiCMS template.

2025-11-08

Can the `join` filter in AnQiCMS template handle array elements containing Chinese characters correctly? If so, what are the precautions?

In AnQiCMS template development, the `join` filter is a very practical tool that can concatenate all elements of an array (or slice) with a specified separator to form a single string.For many users concerned, can the `join` filter correctly handle array elements containing Chinese characters? The answer is affirmative.AnQiCMS is developed based on Go language, Go language supports UTF-8 encoding natively, which means it has a natural advantage in handling multi-language characters. Therefore

2025-11-08

What will happen when the `join` filter encounters an array with mixed data types (such as strings and numbers)?

In Anqi CMS template development, the `join` filter is a very useful tool that can help us concatenate multiple elements of a list (array) into a complete string.This is particularly convenient when it is necessary to display a series of related data in a unified format, such as displaying multiple tags of articles, multiple characteristics of products, or multiple permissions of users.However, in practice, we sometimes encounter situations where the array to be concatenated contains different types of data, such as strings, numbers, and even boolean values. So

2025-11-08

How to customize fields in the AnQiCMS backend where a field stores multiple choices (an array), and clearly display them on the frontend page using the `join` filter?

The AnQi CMS provides great convenience for website operators with its flexible content model and powerful custom features.In daily content management, we often encounter situations where we need to add multiple selection properties to articles or products, such as a product may have multiple colors, different sizes, etc.How to display them in a clear and beautiful way on the front-end page when this information is stored in the background through custom fields in the form of multi-select values has become the problem we need to solve.### Understanding the Multi-Select Custom Fields in AnQi CMS On the AnQi CMS backend

2025-11-08