How to combine the `split` filter to split a string into an array of words for counting or traversal?

Calendar 👁️ 80

In the daily content operation of Anqi CMS, we often encounter scenarios where we need to handle string data, such as keyword lists of articles, content tags, or some multi-value custom fields stored in a specific format.These data often exist in the form of a single string, but when displayed on the front-end, we hope they can be presented in a more flexible and structured manner, such as independent label blocks, clickable links, or need to count the number of elements within them.

At this time, the Anqi CMS template has built-insplitThe filter has become a very practical tool. It can help us easily split a long string into an array or list of multiple segments according to the specified delimiter, thereby laying the foundation for subsequent statistics, traversal, or further processing.

splitFilter: Turns string into zero

Imagine you have a series of keywords connected by commas, like "AnQi CMS, content management, Go language". If notsplitThe filter, you may find it difficult to handle each keyword individually in the template. AndsplitThe filter acts like a pair of scissors, able to precisely cut the string of keywords according to the "cut point" (delimiter), into a list consisting of three independent elements such as "AnQi CMS", "Content Management", and "Go Language".

Its basic usage is very intuitive: you just need to pass the string through a pipe|pass tosplitfilter, and specify your delimiter after the filter with a colon. For example:

{% set keyword_string = "安企CMS,内容管理,Go语言" %}
{% set keyword_list = keyword_string|split:"," %}
{# 此时,keyword_list 会是一个包含 ["安企CMS", "内容管理", "Go语言"] 的数组 #}

It is worth noting that the delimiter you choose must match the delimiter in the actual string. If your keywords are separated by 'comma space', such as 'AnQi CMS, Content Management, Go language', then the delimiter should also be',This is not a single quotation mark,If the string does not contain the specified separatorsplitThe filter will treat the entire string as a single element and return an array containing only this one element.

Combineforloop andlengthThe filter performs statistics and traversal

Once a string has beensplitInto an array, we can use the powerful Anqi CMS template toforloop andlengthThe filter to display and statistically analyze the data flexibly.

Traverse and display the keyword list

Assume your article detail page has onearchive.KeywordsField, its value is "SEO optimization, website promotion, content marketing". You want to display these keywords in the form of independent tags at the bottom of the page. You can do this:

{% set article_keywords = archive.Keywords %} {# 假设值为 "SEO优化,网站推广,内容营销" #}
{% if article_keywords %}
    <div class="keywords-list">
        <strong>文章关键词:</strong>
        {% set keyword_array = article_keywords|split:"," %}
        {% for keyword in keyword_array %}
            {# 注意:这里我们使用 |trim 过滤器来移除每个关键词可能存在的首尾空格,确保显示整洁 #}
            <span class="keyword-tag">{{ keyword|trim }}</span>
        {% endfor %}
    </div>
{% endif %}

This, each keyword will be extracted and displayed separately in a label with.keyword-tagstyled one.<span>which is both beautiful and convenient for users to click or recognize.

Count the number of keywords

If you want to know how many keywords an article has,splitFilter combinationlengththe filter can easily achieve it.lengthThe filter is used to get the length or quantity of strings, arrays, or objects.

{% set article_keywords = archive.Keywords %} {# 假设值为 "SEO优化,网站推广,内容营销" #}
{% if article_keywords %}
    {% set keyword_array = article_keywords|split:"," %}
    <p>这篇文章包含了 <strong>{{ keyword_array|length }}</strong> 个关键词。</p>
{% endif %}

Through these two steps, you can intuitively display the total number of keywords in the article.

In-depth mining and processing

splitIts use is not limited to this. If your custom fields store multi-value data that needs special processing, such as "Color: red, green, blue" or "Size: S, M, L, XL", you can use them first.splitSplit them into an array and then combineifWith conditional judgment or nestedforLoop to implement more complex display logic.

For example, a custom field of a product modelproduct_optionsPossibly contains "Material: Cotton and Linen; Color: Red, Blue, Green; Size: M, L". This is needed twicesplit: Split options once by semicolon, and then split the values of each option by comma.

{% set product_options_string = product.CustomOptions %} {# 假设值为 "材质:棉麻;颜色:红,蓝,绿;尺寸:M,L" #}
{% if product_options_string %}
    <ul class="product-options">
        {% set options_array = product_options_string|split:";" %}
        {% for option_pair in options_array %}
            {% set pair_parts = option_pair|split:":" %}
            {% if pair_parts|length == 2 %}
                <li>
                    <strong>{{ pair_parts[0]|trim }}:</strong>
                    {% set values_string = pair_parts[1]|trim %}
                    {% set values_array = values_string|split:"," %}
                    {% for value in values_array %}
                        <span class="option-value">{{ value|trim }}</span>
                    {% endfor %}
                </li>
            {% endif %}
        {% endfor %}
    </ul>
{% endif %}

This example shows how to use it multiple times.splitandforLoop, parse complex formatted string data and present it in a structured way on the front end.

Summary

splitThe filter is a powerful and flexible data processing tool in Anqi CMS template. It can organize seemingly chaotic string data into an orderly array, cooperate withforLoop for traversal display, as welllengthThe filter is used for quantity statistics, greatly enhancing the dynamic processing and display of the template. Proficient in usingsplitWill make your content management more efficient, and website content more dazzling.


Frequently Asked Questions (FAQ)

1.splitFilters andmake_listWhat are the differences between filters?

splitThe filter is based on the "delimiter" you specify to split strings. For example,"A,B,C"|split:","You will get["A", "B", "C"]Howevermake_listThe filter splits each character of a string into an element of an array, considering each letter and each Chinese character as one. For example,"你好"|make_listYou will get["你", "好"]In most cases, if you need to separate data by specific symbols (such as commas or semicolons), you should usesplit; if you need to handle individual charactersmake_listit is more convenient.

2.splitWhat are the precautions when the filter is processing a string containing spaces?

If your string contains elements separated by delimiters and spaces, such as "Apple, Banana, Orange", then insplitthere are two common handling methods:

  • Exact matching of delimiters:If you write"苹果, 香蕉, 橘子"|split:", "(

Related articles

Does AnQiCMS's backend content editing feature provide real-time word count similar to `wordcount`?

AnQiCMS (AnQi Content Management System) is an enterprise-level content management system developed based on the Go language, which performs excellently in providing efficient and customizable content management solutions.For content operators, the convenience of the backend editing experience is crucial, and one of the details often paid attention to is the real-time statistics of the number of words or characters in the content.Many content operators often need to pay attention to word count when writing articles, in order to control the length of the article, meet SEO requirements, or comply with specific publishing standards.

2025-11-09

`wordcount` filter can identify and count consecutive non-space characters (such as URLs) as a single "word"?

During the content management process of AnQiCMS (AnQiCMS), we often need to count the number of words in articles in order to better plan content, estimate reading time, or optimize SEO.This is when the `wordcount` filter becomes a very practical tool.

2025-11-09

How to limit the maximum number of words displayed in the AnQiCMS article summary instead of the character count?

When managing content in AnQi CMS, the display method of the article summary (also often referred to as an abstract) is crucial for the overall aesthetics and user experience of the website.A good introduction can attract readers and help search engines understand the content.The AnQi CMS defaults to automatically extracting the first 150 characters of the article content as a summary when publishing article content, if the user has not manually filled in a summary.

2025-11-09

What are the different application scenarios between the `truncatewords` filter and the `wordcount` filter in text processing?

In AnQi CMS, we often need to flexibly handle text to adapt to different display requirements and information communication purposes.Among them, the `truncatewords` and `wordcount` filters are two powerful tools in the hands of content operators.They all seem to be related to 'word count' or 'words', but their actual application scenarios and focuses are quite different.Understanding the differences can help us optimize the presentation of website content more accurately.

2025-11-09

What is the difference between the `count` filter and the `wordcount` filter in counting specific elements in a string?

In Anqi CMS template design, we often need to process various text content on the page, among which counting the elements in a string is a common requirement.Anqi CMS provides two practical filters `count` and `wordcount`, although they are all related to "counting", they have clear distinctions and their own preferred scenarios in practical applications.Understanding these distinctions can help us manage and display website content more accurately and efficiently.

2025-11-09

How to count the occurrences of a specific word in a paragraph in AnQiCMS template?

In AnQiCMS template design, we often encounter the need to analyze content or display it in a specific way, such as counting the number of times a keyword appears in an article.This has practical significance for content operation, SEO optimization, or improving user experience.AnQiCMS provides a flexible and feature-rich template engine, allowing us to easily implement such operations.

2025-11-09

How does the `wordcount` filter count text that contains HTML entities (such as `&nbsp;`)?

When using AnQi CMS to manage website content, we often need to perform word counts on articles, whether it is for content planning, SEO optimization, or simply to meet publishing requirements, the `wordcount` filter is a very practical tool.It can quickly calculate the number of words in text, providing intuitive data support for content operation.

2025-11-09

How to estimate the reading time required by users on the article detail page of AnQiCMS based on the `wordcount` result?

In website operation, we all hope to provide visitors with the best browsing experience possible.One feature that seems trivial but can significantly improve user satisfaction is to estimate the time required for users to read the article details page.This can not only help visitors quickly judge whether there is enough time to read the entire content, but also effectively improve the reading completion rate of the article, thereby indirectly optimizing the user engagement of the website.AnQi CMS is a comprehensive and highly flexible content management system that provides powerful template tags and filters, making it very easy to implement this feature.

2025-11-09