How to calculate the total number of times a specific keyword appears in a line string or an array in the AnQiCMS template?

Calendar 👁️ 65

In AnQiCMS template development, we often need to flexibly handle content on the page.For example, you may need to analyze the frequency of a specific word in an article, or check how many times an element is mentioned in a list.The powerful template engine of AnQi CMS provides a variety of practical filters (Filter) that can help you easily meet these needs.The function to calculate the total number of times a specific keyword or element appears is exactly the focus of our discussion today.

Core function:countFilter Details

In AnQiCMS template, to calculate the total number of times a specific keyword appears in a line string or an array, you can directly usecountFilter. This filter is powerful and easy to use, meeting your various needs in content statistics and conditional judgment.

countThe principle of operation of the filter:

WhencountThe filter is applied to a string, it will precisely match and count the number of times the keyword appears in the string. If applied to an array (or a slice in Go language)sliceIt will count the number of elements in the array that are exactly equal to the specified keyword.

Basic syntax:

{{ obj|count:"关键词" }}

Among them:

  • objRepresents the string variable or array variable you want to count.
  • "关键词"Is the specific string or element you want to count the occurrence of.

It will return an integer value indicating the total number of times the keyword occurs.


Scene one: Count the occurrence of keywords in a string

Imagine you are optimizing the SEO of a website, and you need to understand the density of a core keyword in the article content, or you want to dynamically adjust the page layout or display hints based on the number of times a word appears in the content. At this point,countThe filter can be put to good use.

For example, we have an article title describing an enterprise CMS and we want to count how many times the word “CMS” appears:

{# 假设有一个字符串变量 `articleTitle` 的值为 "欢迎使用安企CMS(AnQiCMS)" #}
{% set articleTitle = "欢迎使用安企CMS(AnQiCMS)" %}
<p>在标题 "{{ articleTitle }}" 中,"CMS" 出现了 {{ articleTitle|count:"CMS" }} 次。</p>

Display result:

在标题 "欢迎使用安企CMS(AnQiCMS)" 中,"CMS" 出现了 2 次。

This example shows thatcountThe filter will find all substrings that match the specified keyword exactly and count them.This is very useful for keyword density analysis, content relevance assessment, or when content operation requires automated processing based on the frequency of specific vocabulary mentions.


Scenario two: count the number of occurrences of a specific element in the array

Besides strings,countThe filter can also handle array data. When dealing with user-submitted tag lists, filter condition selections, or when calculating the distribution of a certain attribute in a dataset, counting the frequency of specific elements in the array is a common requirement.

It should be noted that whencountThe filter is applied to the array, it requires the elements of the array to match the specified “keyword”Perfect match.

For example, assume we have a throughsplitThe filter splits the string into an array of words, how many times does the word 'the' appear:

{# 假设有一个字符串,通过 `fields` 过滤器将其按空格拆分为数组 #}
{% set sentenceWords = "splits the string 安企CMS"|fields %}
<p>在单词数组 "{{ sentenceWords|join:", " }}" 中,"the" 出现了 {{ sentenceWords|count:"the" }} 次。</p>
<p>在单词数组 "{{ sentenceWords|join:", " }}" 中,"安企" 出现了 {{ sentenceWords|count:"安企" }} 次。</p>

Display result:

在单词数组 "splits, the, string, 安企CMS" 中,"the" 出现了 1 次。
在单词数组 "splits, the, string, 安企CMS" 中,"安企" 出现了 0 次。

It can be seen from the second example that although the original string contains "安企CMS", when it isfieldsAfter splitting the filter, "AnQi CMS" becomes an independent element.If you only search for 'AnQi', since there are no completely matching independent elements, the count result will be 0.This emphasizescountThe "exact match" principle of the filter under the array scenario.

Precautions for use

  • Case Sensitive: countThe filter performs an exact match, so it is case-sensitive by default.For example, "CMS" and "cms" are considered two different keywords.If you need to perform a case-insensitive count, you may need to convert the source string and keywords to a uniform case (such as lowercase) before counting, but this requires combining with other filters to implement, and there is no direct support for this conversion filter in the default template tags of Anqi CMS.
  • Exact match:Whether it is a string or an array,countthe filter requires an exact match. For strings, it is an exact substring match; for arrays, it is an exact element match.
  • Combine with other filters:As shown in the above example, you can use:splitorfieldsAnd other filters with:countCombine filters to split a long string into an array first, and then count the elements in the array.
  • Performance consideration: For frequent statistics of extremely long strings or large arrays, although Go language is excellent in backend performance, but overly complex template logic may still have a slight impact on the speed of page rendering.In most routine usage scenarios, there is no need to worry too much.

By mastering the use ofcountFilter, you will be able to process and analyze data more efficiently in the AnQiCMS template, providing strong support for the dynamic display and refined operation of website content.


Frequently Asked Questions (FAQ)

1.countDoes the filter distinguish between uppercase and lowercase letters when counting keywords?Yes,countThe filter is case sensitive by default. For example, if you search for "CMS", it will not count the occurrences of "cms" or "Cms".If you need to perform case-insensitive statistics, you may need to convert both the text content and the keywords you want to count to a uniform case format, but this requires a custom template function or backend processing.

How to count the total occurrences of multiple different keywords in a long string? countThe filter can only count the occurrences of a specific keyword at a time. If you need to count multiple different keywords, you can call for each keyword separately.countThen add the results of them. For example:{{ (articleContent|count:"关键词A") + (articleContent|count:"关键词B") }}.

3. If I only want to check if a keyword exists in a string or array instead of counting the specific number of times, is there a more concise way?Of course, AnQiCMS provides.containThe filter is used to determine if it exists. If you just need to know if a certain keyword exists, use.{{ obj|contain:"关键词" }}It will be more efficient and concise, it will return.TrueorFalse.

Related articles

How to determine if the length of a variable in the AnQiCMS template matches the expected value and make a judgment in the conditional statement?

In website content management, flexibly controlling the way content is displayed is crucial for improving user experience and page aesthetics.AnQiCMS (AnQiCMS) provides a powerful template engine, allowing us to easily determine how to display page elements based on the characteristics of the content, such as the length of a variable.When you need to judge whether the length of a variable meets the expected requirements and perform different operations in the template based on this, the template tags and filters of Anqi CMS provide an intuitive and efficient solution.Flexible control of content display: The importance of length judgment Imagine one

2025-11-08

How to get the actual length of a string or array in AnQiCMS template (number of characters or elements)?

When managing website content in AnQi CMS, you often encounter situations where you need to get the number of characters in text or determine how many elements are in a list or array.In order to control the page layout, ensure the display length of the title introduction, or dynamically adjust the display logic based on the amount of data, it is crucial to understand how to obtain this "length" information in templates for creating flexible and user-friendly websites.The AnQi CMS template engine provides a concise and powerful way to handle such requirements, with the most core being the `length` filter

2025-11-08

The `make_list` filter and the `split` filter are applicable to which scenarios in converting strings to character arrays in AnQiCMS templates?

In AnQiCMS template development, we often need to process string type data, where converting a string to an array is a common requirement.AnQiCMS powerful template engine provides a variety of filters to assist in completing such tasks, among which the `make_list` and `split` filters are the tools for converting strings to arrays.Although they can both 'turn' strings into arrays, there are essential differences in their application scenarios and conversion logic.Understanding these differences can help us achieve template functionality more efficiently and accurately.##

2025-11-08

How to split a string containing multiple keywords in AnQiCMS template by spaces, commas, or a custom delimiter into an array?

In AnQiCMS (AnQiCMS) content management and template development, we often encounter scenarios where we need to process strings containing multiple keywords.For example, an article may have a comma-separated list of keywords, or product attributes are space-separated tags.Make full use of these data and display them flexibly in the template, you need to split these strings into traversable arrays precisely.AnQiCMS uses a template engine syntax similar to Django, providing powerful filter functions to handle such needs.Among, `split`

2025-11-08

How to batch remove leading, trailing spaces or specific characters from AnQiCMS template strings for data cleaning and formatting?

When using AnQiCMS for website content management, we often encounter situations where we need to fine-tune the text output in templates.Whether it is data obtained from a database or content entered in an editor, it may contain extraneous spaces, line breaks, or even specific characters that are not intended to be displayed.In order to ensure the tidiness, consistency of website content, and to enhance user experience and search engine friendliness, it is particularly important to clean and format the data.AnQiCMS provides a flexible and powerful template engine, its syntax is similar to Django

2025-11-08

What are the common practical application scenarios for the `cut` filter when removing specified characters from any position in the AnQiCMS template string?

In AnQiCMS template design, in order to present the content effect that best meets expectations, we often need to process strings finely.Among the many built-in filters, the `cut` filter is a seemingly simple yet extremely practical tool.Its core function is to remove the specified characters from any position in the template string, which makes it have a unique application value in content cleaning, formatting, and enhancing the user reading experience.The `cut` filter works very directly: it traverses the target string and removes all segments that match the specified character

2025-11-08

How does AnQiCMS handle automatic line breaks for long articles or description text to improve the readability of the front-end page?

In website content operation, the presentation effect of long articles or large sections of descriptive text directly affects the user's reading experience.If content is piled together without good layout and proper line breaks, even the most精彩 content will make readers reluctant.AnQiCMS is a content management system that focuses on user experience and provides various mechanisms to cleverly handle automatic line breaks in long texts, thereby greatly improving the readability of the front-end pages.### Basic Coverage: Markdown Editor and Natural Line Breaks Firstly, AnQiCMS is well-supported by the built-in Markdown editor.

2025-11-08

How to automatically scan and convert ordinary text content in the AnQiCMS template into clickable URL links or email addresses?

In website content operation, we often need to display some URLs or email addresses in articles or pages. If these addresses are only in plain text, users cannot directly click to jump, which not only affects the user experience but may also make search engines difficult to recognize these valuable link information.Fortunately, AnQiCMS provides a very convenient set of built-in features that can help us automatically convert ordinary text content into clickable hyperlinks or email links, making the website content more interactive and professional.To implement this feature, we mainly use AnQiCMS

2025-11-08