In AnQi CMS, content operation often needs to handle diverse inputs from users.For example, we may need to allow users to enter multiple keywords as tags on article or product detail pages, which are usually connected by commas or other delimiters.However, in order to display these tags in a beautiful and interactive 'tag cloud' form on the front-end page, each tag needs to be uniquely identifiable and may be accompanied by individual links.At this point, converting the single string input by the user into an operable array format has become an important task in template development.splitFilter, able to elegantly solve this problem.

Tag management and requirements in Anqi CMS.

The AnQi CMS backend allows us to add 'Tag tags' to articles, products, and other content. These tags can be manually entered or selected from an existing keyword library. When adding documents in the backend, we will usually see 'Please use English for multiple keywords between them,',to distinguish such hints.This means that, whether it is the built-in tag function of the system or the tags freely input by users through custom fields, they may be stored in the form of a string containing multiple tags, separated by a specific delimiter.

For example, an article may have a nameduser_tags

splitFilter登场:将字符串变成数组

splitThe filter plays a key role in the Anqi CMS template engine, its main function is to split a string into an array according to the specified delimiter.This filter is very flexible, capable of handling various delimiters, thus converting the user input label string into an array that is easy for the front-end template to traverse and render.

Its basic usage is like this: You have a string variable, and then through the pipeline|连接splitFilter, and specify the delimiter in quotes.

Basic syntax example:

{# 假设 rawTags 是一个包含逗号分隔标签的字符串 #}
{% set rawTags = "安企CMS,网站运营,内容管理" %}
{# 使用 split 过滤器将其按逗号分隔成数组 #}
{% set tagsArray = rawTags | split:"," %}
{# 打印查看转换后的数组,这在开发调试时非常有用 #}
{{ tagsArray | stringformat:"%#v" }}

In the above example,tagsArrayIt will become an array containing["安企CMS", "网站运营", "内容管理"]these three elements. It is worth noting that,splitThe filter returns an array containing the original string itself if the delimiter itself does not exist in the string during the split operation.If the delimiter is an empty string, it will split each character of the string into an element of the array.

Actual application: Creating a dynamic tag cloud

UnderstoodsplitAfter the filter's effect, we can apply it to the actual construction of the tag cloud. Suppose we have a namedcustomTagsThe custom field used to store comma-separated tags entered by the user. Here is an example of how to convert it into a tag cloud in a template:

{# 假设 archive.CustomTags 是存储用户输入的标签字符串的变量 #}
{% set userTagsString = archive.CustomTags %}

{# 首先,检查 userTagsString 是否存在且不为空 #}
{% if userTagsString %}
    {# 使用 split 过滤器将字符串按逗号和空格(或仅逗号)分隔成数组。
       这里使用 ", " 可以同时处理 "tag1, tag2" 和 "tag1,tag2" 的情况,更健壮。
       也可以只用 ",",如果用户严格按此输入的话。 #}
    {% set tagsArray = userTagsString | split:", " %}

    <div class="tag-cloud">
        {# 遍历生成的标签数组 #}
        {% for tag in tagsArray %}
            {# 在处理每个标签之前,先去除首尾空格,并确保标签不为空。
               然后,为每个标签生成一个链接,这里假设链接到网站的搜索功能。 #}
            {% if tag | trim != "" %}
                <a href="/search?q={{ tag | trim | urlencode }}" class="tag-item">
                    {{ tag | trim }}
                </a>
            {% endif %}
        {% endfor %}
    </div>
{% else %}
    <p>该内容暂无自定义标签。</p>
{% endif %}

In this code, we first obtain the label string entered by the user. Then, we usesplit:", "Split it into an array. While traversing the array, we also cleverly combined several other filters:

  • trimThis filter can remove leading and trailing spaces from a string. The user may accidentally enter extra spaces when typing (for example, "Label A, Label B"),trimIt can help us clean up these unnecessary whitespace characters, ensuring the tidiness of the label content.
  • urlencode: When constructing the jump link of the tag, in order to avoid special characters (such as spaces, Chinese characters, etc.) in the tag content causing URL parsing errors, useurlencodeThe encoding of label text by the filter is an essential step to ensure the validity of the link.

Through such processing, the originally simple string is converted into a series of clickable, customizable styled tags, greatly enhancing the dynamic display ability and user experience.

Cautionary notes and **practice

While usingsplitWhen filtering, there are several minor details and **practices that are worth paying attention to:

  1. Consistency of delimiters:Make sure the delimiter you use in the template matches the delimiter required by the user input or backend settings. Common ones include the English comma,, an English comma followed by a space,, or a vertical line|If the delimiter is inconsistent, the cutting result may not meet the expected.
  2. Handle empty tags:Users may enter content like "Tag1,,Tag2" or "Tag1, ,Tag2", resulting insplitan empty string being created. By{% if tag | trim != "" %}Such a judgment can effectively filter out these invalid empty tags, preventing them from displaying on the front end.
  3. Filter chaining call:As shown in the above example,splitFilters are often used with other filters (such astrim/urlencodeCombine them to form a processing chain to achieve a more refined and robust data processing effect.

By reasonable applicationsplitFilter, you can easily convert the flat label string entered by the user into structured array data, bringing more flexibility and dynamic feel to the content display of the Anqi CMS website.


Frequently Asked Questions (FAQ)

Q1: If the user's input label is not separated by commas but by other symbols, such as a vertical line|or a semicolon;, how should I handle it?

A1: splitThe filter supports custom delimiters. You just need tosplitThe delimiter parameter in the filter can be modified to the delimiter actually used by the user. For example, if the user uses the pipe delimiter, you can write it as{% set tagsArray = userTagsString | split:"|" %}.To enhance robustness, you can also consider prompting users to use a uniform delimiter in the background, or preprocessing and standardizing through JavaScript before submitting on the frontend.

Q2: I see that the Anqi CMS backend has a 'Tag Management' feature, how is it different from the tags processed here? Which one should I use?splitWhat is the difference between the tags processed? Which one should I use?

A2:The 'Tag Management' in AnQi CMS backend is a native feature used to manage and display structured tags associated with articles, products, and other content. These tags usually have independent IDs, links, and detail pages, and can be accessed viatagListLabel directly call. InsteadsplitThe tags processed by the filter, which are usually the free text entered by the user in the custom fields, they are essentially part of the content, the Anqi CMS system itself will not pass these throughsplitThe individual processed by the filter