In website content operation, we often encounter such situations: a certain content field stores a series of interrelated information, which is 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 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 the template development of AnQiCMS (AnQi CMS).

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

ingeniously utilizesplitFilter: The key to convert a string to an array

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

Its basic usage is very intuitive:

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

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

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

Firstly, let's use:settags toarticle.TagsAssign its value to a new variabletagStringThis is usually for code readability. Then, we settagStringto be appliedsplita filter and specify a comma (,) as the delimiter, and store the results intagArray.

CombineforLoop tags: Traverse the array and display the content

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

forThe basic syntax of loops is:

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

Now, we willsplitFilter is related toforCombined 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 will be split.tagListArray. Next,forThe loop will iterate over thetagListeach of themtag. Inside the loop, we created a link for each tag, and here we especially used|trimFilter to remove any leading or trailing spaces that may be present on tags, making the display neater.|urlencodeFilter ensures that tags are encoded correctly when used as URL parameters.{% empty %}Branch handles gracefully whentagListThe display situation when it is empty (i.e., the original string is empty or no valid elements are obtained after cutting).

Examples of practical scenarios

  • Multi-label display:The detail page of the website article, displaying all related tags of 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 URLs of multiple images and needs to be loaded and displayed one by one.

Advanced hint:make_listFilter

Exceptsplitbeyond that, the Anqi CMS also providesmake_listFilter.make_listThe function of this is to split a string by characters, and each character is placed as an independent element in the 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, as it treats the comma itself as a character, but it can be 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 skillfully utilizingsplitThe filter converts a comma-separated string into an array and combinesforPerforming a loop traversal, you can easily present structured or semi-structured data from the backend in a clear and beautiful manner on the website front-end. At the same time,配合trim/urlencodeAn auxiliary filter, which can further optimize the display effects and functionality of the content.Master these skills, and it will greatly enhance your efficiency in content operation and template development on AnQi CMS.


Common Questions and Answers (FAQ)

Q1: If my original string is like"标签A, 标签B, 标签C", there is a space after the comma,|split:","how should it be handled?A1: If the original string is"标签A, 标签B, 标签C"and you use|split:","Perform the cut, you will get something like["标签A", " 标签B", " 标签C"]This array. Note that the elements after the cut" 标签B"and" 标签C"will keep that space in front. To ensure a neat display effect,forLoop internally processes each element|trimFilter, for example{{ tag|trim }}It will automatically remove spaces at the beginning and end of the string.

Q2: How do 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 determine if the original string is empty before the split, for example{% if article.Tags %}。If the original string is empty, it will not be split. Another method is to handle the case where the array is empty, for exampleforuse in a loop.{% empty %}分支来处理数组为空的情况,例如{% for tag in tagList %}{#...#}{% empty %}<li>没有标签</li>{% endfor %}.

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