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:"," }},