How to use the `fields` filter to extract all 'words' from a string and further process them?

Calendar 👁️ 66

In AnQiCMS, content operators often need to flexibly handle and display text information.Sometimes, we may need to extract all the 'words' from a long string, whether it is for keyword analysis, making tag clouds, or simply for reorganizing content display.At this time, the AnQiCMS template system provides a very practical tool——fieldsA filter that can help us easily achieve this goal.

fieldsA filter: converts a string into an array of 'words'

The AnQi CMS template system, inspired by the powerful syntax of Django template engine, makes content processing intuitive and efficient.fieldsThe filter is an example of this, its core function is to split a text string by spaces and convert it into an iterable string array.This means, it treats each substring separated by a space as a 'word'.

Imagine you have a content variable that contains descriptions similar to 'AnQiCMS is an enterprise-level content management system developed based on the Go language.'If you want to process or display each word in this sentence individually, it would be difficult to do so directly.However, throughfieldsFiltering, this process becomes very simple:

{% set content_string = "AnQiCMS 是一个基于 Go 语言开发的企业级内容管理系统" %}
{% set words_array = content_string|fields %}
{# 此时,words_array 会包含一个类似这样的数组:
   ["AnQiCMS", "是一个", "基于", "Go", "语言开发的企业级", "内容管理系统"]
#}

As you can see,fieldsThe filter effectively split the original string into multiple parts by spaces and stored them in a namedwords_array.

Further processing extracted the "word"

Once we convert the string into an array, we can use the loop and conditional judgment functions provided by the AnQiCMS template system to flexibly process these 'words'.

1. Traverse and display

The most basic application is to traverse this array and display each 'word' individually.For example, you might want to add some style to each word or organize them into a list.

<div class="word-list">
    {% for word in words_array %}
        <span class="highlight-word">{{ word }}</span>
    {% endfor %}
</div>

Thus, each extracted "word" will be wrapped in a tag withhighlight-wordstyled one.<span>label for easy style control on the front-end.

2. Concatenate and combine

Sometimes, we may need to reassemble these extracted "words" into a new string, but with different delimiters. At this time,joinThe filter comes into play. For example, you might want to connect all words with commas and spaces:

<p>重新拼接后的内容:{{ words_array|join(", ") }}</p>
{# 输出可能为:AnQiCMS, 是一个, 基于, Go, 语言开发的企业级, 内容管理系统 #}

This is very useful when generating keyword tags or adjusting the display format.

3. Counting and Searching

Understanding how many 'words' are extracted, or checking for the existence of a specific 'word', is also a common requirement.

  • Calculate the total:UselengthThe filter can easily obtain the total number of "words" in the array.

    <p>这段内容总共提取了 {{ words_array|length }} 个“单词”。</p>
    
  • Search for a specific word: containThe filter can help you determine whether the array contains an exact match of the "word".

    {% if words_array|contain:"内容管理系统" %}
        <p>页面内容中提到了“内容管理系统”这个重要的词。</p>
    {% else %}
        <p>页面内容中未包含“内容管理系统”。</p>
    {% endif %}
    

    Furthermore,countThe filter can calculate the number of times a specific matching "word" appears in an array.

    <p>“Go”这个词在内容中出现了 {{ words_array|count:"Go" }} 次。</p>
    

4. Conditional judgment and filtering

You can also combine conditional judgment to perform special processing on certain 'words'. For example, when a word appears, give it a special color or style:

<div class="processed-text">
    {% for word in words_array %}
        {% if word == "AnQiCMS" or word == "Go" %}
            <strong style="color: blue;">{{ word }}</strong>
        {% else %}
            {{ word }}
        {% endif %}
    {% endfor %}
</div>

This code will iterate over all "words", and if it encounters "AnQiCMS" or "Go", it will be displayed in bold blue, and the rest will be displayed normally.

fieldsthe filter meetssplitThe difference between filters

It is worth noting that,fieldsThe filter defaults to using one or more spaces as separators. This means that if the 'words' in your string are separated by other characters (such as commas, semicolons, pipes, etc.), thenfieldsThe filter may not achieve the effect you expect.

In this case,splitThe filter will be a more flexible choice.splitThe filter allows you to specify any delimiter to split a string into an array. For example, if your keywords are "SEO optimization, website promotion, content marketing":

{% set keywords_string = "SEO优化,网站推广,内容营销" %}
{% set keywords_array = keywords_string|split(",") %}
{# 此时 keywords_array 会包含:["SEO优化", "网站推广", "内容营销"] #}

<div class="keyword-tags">
    {% for keyword in keywords_array %}
        <span class="tag">{{ keyword|trim }}</span>{# 使用 trim 过滤器去除可能存在的多余空格 #}
    {% endfor %}
</div>

Here, we use the comma assplita separator for the filter, successfully extracting keywords separated by commas.

Summary

fieldsThe filter is a seemingly simple but powerful tool in the AnQiCMS template system, which makes it easy to extract 'words' from strings and perform subsequent processing. Whether it is for content analysis, dynamic display, or better management of page information, masteringfieldsand relatedjoin/length/contain/count/splitAll filters can significantly improve your content operation efficiency and website flexibility. Encourage you to try them out more in practice and discover more uses in different scenarios.


Frequently Asked Questions (FAQ)

  1. Question:fieldsCan the filter only be split by spaces? What should I do if my words are separated by other symbols, such as commas?Answer: Yes,fieldsThe filter is specifically used to split strings by spaces (including multiple consecutive spaces). If your "words" are separated by commas, semicolons, pipes, and other symbols, you should usesplitfilter.splitThe filter allows you to specify any character as a delimiter, for example{{ your_string|split(",") }}.

  2. Question:fieldsWill the 'word' extracted by the filter contain punctuation?Answer:fieldsThe filter is separated by spaces. This means that if a "word" is next to a punctuation mark (such as "system.")Or (AnQiCMS), and if it is without spaces between the next word, then these punctuation marks will be considered as part of the word.If you need to remove these punctuation marks, you may need to combinereplaceorcutand other filters are processed twice.

  3. Ask: Is the 'word' array case-sensitive?Yes, the AnQiCMS template system is case-sensitive by default when processing strings.This means that if your array contains "CMS" and "cms", they are considered two different "words".If you need to perform case-insensitive processing, you can uselowerorupperThe filter converts all strings to

Related articles

How does the `wordcount` filter affect the performance overhead for long text? Will it affect the page loading speed?

In the daily operation of AnQi CMS, we all pay close attention to the performance of the website and the page loading speed, especially when dealing with a large amount of content.Regarding whether the `wordcount` filter will bring significant performance overhead and its impact on page loading speed is a common question.Today, let's delve deeply into this topic. ### Understanding the `wordcount` filter and its working principle First, let's clarify the role of the `wordcount` filter.

2025-11-09

How does the `pluralize` filter correctly display the singular and plural form of a word based on the `wordcount` value?

In website content operation, details often significantly enhance user experience.One common but often overlooked detail is how to correctly display the singular and plural forms of words based on quantity.Imagine seeing the display 'You have 1 message' and 'You have 2 messages', isn't it much more natural and fluent than seeing 'You have 1 messages' or 'You have 2 message'?

2025-11-09

How to dynamically adjust the length of the article abstract based on the number of words in the AnQiCMS template?

In website content operation, the article abstract is like a business card of the article, it can catch the reader's attention at the first time, helping them quickly understand the main theme of the article, thus deciding whether to delve deeper into reading.A well-designed summary can not only improve the user experience, but also be of great benefit to search engine optimization (SEO).However, faced with a massive amount of articles, how to ensure that the summary is both accurate and concise, flexible to adapt to different lengths of articles, and avoid being too long or too short, is a challenge faced by many operators.

2025-11-09

How to use the `wordcount` filter in page titles and descriptions to ensure SEO keyword density?

## How to skillfully use AnQiCMS's `wordcount` filter to accurately control the keyword density of page titles and descriptions The importance of page titles (Title) and descriptions (Description) in website operations and Search Engine Optimization (SEO) practices is self-evident.They are not only the information that users see first in search results, which directly affects the click-through rate, but are also key signals for search engines to understand the core theme of the page content.To make the page stand out among competitors, control the keyword density in the title and description reasonably

2025-11-09

In AnQiCMS content management, after batch replacing keywords, will the `wordcount` result be automatically updated?

In content management, efficiency and accuracy are the core concerns of operators.AnQiCMS is a feature-rich CMS that provides various tools to simplify content maintenance.Among them, the batch keyword replacement function greatly improves the efficiency of content adjustment, while word count (`wordcount`) is an important indicator of content length.Around these two features, users often wonder: Will the word count automatically update after the content has been replaced with batch keywords?

2025-11-09

What effect will be produced when the `wordcount` filter is combined with the `add` filter?

AnQiCMS with its flexible and powerful template system makes the presentation and data processing of website content very efficient.In the process of template development, skillfully combining various filters often unlocks unexpected practical effects.Today, let's delve deeply into two seemingly basic filters that, when combined, can produce wonderful effects: `wordcount` and `add`.

2025-11-09

How to display the first or last word of a string in AnQiCMS template?

In website content operation, we often need to refine the control of displayed information.Sometimes, a title may be long, and we only want to display the first word in a specific area, or highlight the last word for some design needs.AnQiCMS (AnQiCMS) provides a powerful and flexible template engine, which draws on the essence of Django template syntax, allowing us to achieve these seemingly complex text processing requirements through simple filters (Filters).Today, let's talk about how to use the AnQiCMS template

2025-11-09

What is the result returned by the `wordcount` filter for an empty string or a string that only contains spaces?

The template engine of AnQiCMS (AnQiCMS) provides a series of practical filters to help us flexibly handle data on the front-end page.Among them, the `wordcount` filter is a tool used to count the number of words in a string, which is often used in content operation to ensure that articles meet specific word count requirements or for content analysis.When discussing the `wordcount` filter, a common question is: what kind of result will it return when it encounters an empty string or a string that only contains spaces?

2025-11-09