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

Calendar 👁️ 80

In website content operation, we often encounter such situations: a content field stores a series of interrelated 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 custom keywords defined by the user.When we need to display these comma-separated strings one by one on the front-end page or perform more complex processing, how to efficiently convert them into a traversable data structure is a common requirement in AnQiCMS template development.

The Anqi CMS provides a very elegant and practical solution for this requirement with its powerful performance based on Go language and a flexible syntax similar to the Django template engine.By skillfully using the built-in "filter" and "loop tags", we can easily achieve string splitting and traversal.

Skillfully usesplitFilter: The key to converting a string to an array

To convert a comma-separated string into an iterable array, in the Anqi CMS template,splitThe filter is a core tool.splitThe filter's function is as its name implies, it can split a string into an array according to the delimiter you specify (usually corresponding to the Slice type in Go language).

Its basic usage is very intuitive:

{{ 你的字符串变量|split:"你的分隔符" }}

For example, suppose you have a variablearticle.TagsIts value is"安企CMS,模板开发,Go语言"If you want to split it into an array of three elements, you can use:

{% set tagString = article.Tags %} {# 假设 article.Tags 的值为 "安企CMS,模板开发,Go语言" #}
{% set tagArray = tagString|split:"," %}
{# 此时 tagArray 就是一个数组,例如:["安企CMS", "模板开发", "Go语言"] #}

Here, we first use:setLabels willarticle.TagsAssign the value to a new variabletagStringThis is usually for code readability. Then, we applytagStringthesplita filter and specify the comma (,) as the delimiter, storing the result intagArray.

CombineforLoop tags: Traverse the array and display the content

Once we have successfully converted a comma-separated string into an array, the next step is to use the Anqie CMS template.forLoop tags to process each element in the array one by one.forLoops are the standard way to traverse collection types of data (such as arrays or lists).

forThe basic syntax of loops is:

{% for 元素变量 in 你的数组变量 %}
    {# 在这里处理每个元素 #}
{% empty %}
    {# 如果数组为空,执行这里的代码 #}
{% endfor %}

Now, we willsplitthe filter meetsforCombined with loops, to achieve complete functionality:

{% set articleTags = archive.Tags %} {# 假设 archive.Tags 的值为 "SEO,网站优化,内容营销" #}

{% if articleTags %} {# 先判断字符串是否为空,避免对空字符串进行切割 #}
    {% set tagList = articleTags|split:"," %}
    <div class="article-tags">
        <strong>标签:</strong>
        <ul>
        {% for tag in tagList %}
            <li><a href="/tag/{{ tag|urlencode }}" title="{{ tag }}">{{ tag|trim }}</a></li>
        {% empty %}
            <li>暂无标签</li>
        {% endfor %}
        </ul>
    </div>
{% endif %}

In this example, we first check:articleTagsIs there any content. If there is, it should be cut intotagListan array. Next,forThe loop will iterate overtagListeachtag. Inside the loop, we create a link for each tag, and here we particularly use|trimThe filter removes any leading or trailing spaces that may be present in the label, making the display cleaner.|urlencodeThe filter ensures that the label is encoded correctly when used as a URL parameter.{% empty %}The branch handles the case elegantly whentagListEmpty (i.e., the original string is empty or no valid elements are obtained after slicing).

Example of practical scenarios

  • Display multiple tags:The article detail page of the website, displaying all tags associated with the article.
  • Product Features List:Product details page, listing all product features, such as 'waterproof, shockproof, long-lasting battery life'.
  • Image URL list:A field stores the URLs of multiple images and needs to be loaded one by one.

Advanced hint: make_listFilter

exceptsplitthe following, Anqi CMS also providesmake_listfilter.make_listThe function is to split a string by character, and each character is placed as a separate element in an array.

For example:

{% set text = "AnQiCMS" %}
{% set charArray = text|make_list %}
{# 此时 charArray 就是 ['A', 'n', 'Q', 'i', 'C', 'M', 'S'] #}

{% for char in charArray %}
    <span>{{ char }}</span>
{% endfor %}
{# 输出:<span>A</span><span>n</span><span>Q</span><span>i</span><span>C</span><span>M</span><span>S</span> #}

make_listIt is not commonly used when processing comma-separated strings because it treats the comma itself as a character, but it is very useful in special scenarios where text needs to be processed character by character.

Summary

The AnQi CMS template provides powerful and flexible tools to handle various content display needs. By proficiently usingsplitThe filter converts comma-separated strings into arrays and combines withforLoop through, you can easily display structured or semi-structured data stored on the back-end in a clear and beautiful way on the website front-end. At the same time, cooperate withtrim/urlencodeAn auxiliary filter, which can further optimize the display effect and functionality of the content.Master these skills, and it will greatly enhance your efficiency in content operation and template development on Anqi CMS.


Frequently Asked Questions (FAQ)

Q1: If my original string is like"标签A, 标签B, 标签C"like this, there is a space after the comma,|split:","How will it be handled?A1: If the original string is"标签A, 标签B, 标签C"and you use|split:","cut, you will get something like["标签A", " 标签B", " 标签C"]such an array. Note, the elements after cutting" 标签B"and" 标签C"the space at the beginning is preserved. To ensure a neat display, it is recommended toforuse each element inside the loop.|trimFilter, for example{{ tag|trim }}It will automatically remove spaces from the beginning and end of the string.

Q2: How can I determine if the split array is empty, or if the original comma-separated string is empty?A2: How many ways are there. The most direct method is to judge whether the original string is empty before cutting, for example{% if article.Tags %}If the original string is empty, it will not be split. Another method is to handle the empty array case byforUsing a loop{% empty %}branching out, for example{% for tag in tagList %}{#...#}{% empty %}<li>没有标签</li>{% endfor %}.

Q3: Can I merge the array elements after splitting them back into a string?A3: Of course. The Anqi CMS template providesjoinA filter that concatenates the elements of an array using a specified delimiter to regenerate a string. For example, if you have an arraytagArray = ["安企CMS", "模板开发"]You can merge it back into a comma-separated string like this:{{ tagArray|join:"," }},

Related articles

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 always display product prices (floating point numbers) with two decimal places in AnQiCMS templates?

When operating a product display website, you may often encounter situations where you need to display product prices accurately.A professional and user-friendly website often requires a unified display format for product prices, such as always retaining two decimal places, even for integer prices, which are automatically filled with `.00`. AnQiCMS with its flexible template system makes these details handling very convenient.

2025-11-07

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

During the template creation process in Anqi CMS, we often encounter the need to concatenate a certain field from an array (or list) queried from the database using a specific symbol to form a continuous string for beautiful display on the page, such as connecting multiple tags (Tag) of an article or displaying all the characteristics of a product.The Anq CMS template engine 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

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