How to calculate the number of times a specific keyword appears in a string or array using the `count` filter in AnQiCMS templates?

Calendar 👁️ 73

During the template development process of AnQiCMS, we often need to perform dynamic data analysis or display on the page content, such as counting the frequency of a certain keyword, or checking the number of specific elements in the list. At this time,countThe filter has become a very practical tool. It can help you quickly and efficiently calculate the number of times a specific keyword appears in a string or array, providing the possibility of flexible presentation for templates.


countFilter: Precisely count your content

In short,countThe filter is a powerful tool that can help us count the occurrences of specific keywords in strings (a series of characters) or arrays (a series of data items).This has multi-faceted value for content management. For example, you may need to check the density of a keyword in an article to optimize search engine rankings;Or count the number of times a specific tag is referenced in a document list for content recommendation.No matter what kind of situation,countFilters can provide intuitive statistics.

How to use in AnQiCMS templatecountFilter?

countThe syntax of the filter is very intuitive, following the general rules of the AnQiCMS template engine:

{{ 要统计的变量 | count: "要查找的关键词" }}

Here, 要统计的变量Can be a string containing text, or an array containing multiple items (also known as a slice).要查找的关键词It is the text you want to count the occurrence in the variable. It should be noted that,countThe filter is case-sensitive when matching.

1. Count the number of keywords in a string

When you need to count the frequency of a keyword in a piece of text,countthe filter can be directly applied to the string.

Example:Suppose we have a description of AnQiCMS and want to count the number of times "CMS" appears.

{% set contentText = "欢迎使用安企CMS(AnQiCMS),安企CMS 是一个高效的内容管理系统。" %}
<p>“CMS” 在这段文字中出现了:{{ contentText | count: "CMS" }} 次。</p>

This code will output:“CMS” 在这段文字中出现了:2 次。

2. Count the number of times a specific value appears in an array.

countThe filter function is also applicable to arrays. When you have a data list and want to know how many times a specific value appears, this feature is particularly convenient.

Example:Suppose we obtain a list of keywords in some way and want to count the number of times "AnQi CMS" appears in it. To split a string into an array by spaces, we can first usefieldsfilter.

{% set tagsString = "安企CMS 模板开发 安企CMS 功能强大 SEO优化" %}
{% set tagsArray = tagsString | fields %} {# 使用 fields 过滤器将字符串按空格拆分成数组 #}

<p>数组中 "安企CMS" 出现了:{{ tagsArray | count: "安企CMS" }} 次。</p>
<p>数组中 "功能" 出现了:{{ tagsArray | count: "功能" }} 次。</p>

This code will output:数组中 "安企CMS" 出现了:2 次。 数组中 "功能" 出现了:1 次。

It should be noted that:When performing statistics in the array,countThe filter will performPerfect matchThis means, if there is an element 'Content Management System' in the array, and you are looking for 'system',countThe filter considers "system" as not appearing individually, therefore the count will be 0. Counting will only be performed when the array element matches the keyword exactly.

3. Use conditional judgment for dynamic display

countFilters are usually used in conjunction with other template logic to achieve more complex dynamic display.For example, you can assign the statistical result to a variable and then make a conditional judgment based on the value of the variable.

{% set articleBody = "安企CMS 不仅功能丰富,而且安企CMS 易于上手。我们推荐使用安企CMS。" %}
{% set anqiCmsMentions = articleBody | count: "安企CMS" %}

{% if anqiCmsMentions > 2 %}
  <p class="warning">注意:文章中 "安企CMS" 关键词出现了 {{ anqiCmsMentions }} 次,可能存在过度堆砌风险。</p>
{% elif anqiCmsMentions > 0 %}
  <p class="info">文章中 "安企CMS" 关键词出现了 {{ anqiCmsMentions }} 次,关键词使用恰当。</p>
{% else %}
  <p class="tip">文章中未提及 "安企CMS" 关键词。</p>
{% endif %}

This code can help you perform a preliminary automated assessment of content quality during background management or template preview.

Useful scenarios and advanced thinking

countThe application scenarios of filters are very extensive:

  • SEO keyword density analysis:Quickly check the frequency of core keywords in the article to assist in content optimization.
  • Content review:Count the occurrences of sensitive words, repeated phrases, or specific business terms.
  • Dynamic recommendations: Based on user behavior or page content, count related keywords to recommend more accurate content or products.
  • A/B testing:Compare the use of specific elements in different versions of content.

By flexible applicationcountThe filter allows you to make AnQiCMS templates more dynamic and intelligent, improving the efficiency of content operation and user experience on the website.


Frequently Asked Questions (FAQ)

1.countWhy does the filter sometimes not count the result I want when counting an array?

This is usually becausecountWhat does the filter do in the array?Perfect matchFor example, if your array contains"安企CMS"and you try to count"CMS",The result will be 0. Only when the array element matches the keyword you are looking for (including case),countCounting will be performed. If you need a more flexible substring matching, you can consider concatenating the array elements into a long string and then usingcountThe filter performs statistics.

2.countDoes the filter case-sensitive?

Yes,countIs the filter for matching strings and arraysCase sensitive."AnQiCMS"and"anqicms"It is considered as two different keywords. If your requirement is case-insensitive statistics, you can apply in the applicationcountbefore the filter.lowerorupperThe filter will convert the text to lowercase or uppercase format.

How to count the occurrence of a substring in a string that is not an independent word?

If you want to count the number of occurrences of a substring in a large block of text, regardless of whether it is a separate word, you can directly use thecountfilter. For example,"这是我的一个CMS系统,另一个CMS也很棒" | count: "CMS"It will return 2. If you need to countindependent wordstimes, you can use thefieldsfilter to split the string into an array of words, then use it on the arraycountThe filter performs statistics.

Related articles

In AnQiCMS template, how to add a recommended icon to the article title based on the boolean state of the `item.Flag` attribute?

When managing website content in AnQiCMS, we often hope to highlight important articles through some intuitive visual elements, such as adding a prominent small icon to recommended content.This not only attracts the attention of visitors, but also helps them quickly find high-quality information on the website.It is fortunate that AnQiCMS has built-in `item.Flag` properties and a flexible template engine, making it very easy to implement this requirement.This article will discuss in detail how to use the `item.Flag` attribute status in the AnQiCMS template

2025-11-09

How to determine if the boolean value of a custom field in the AnQiCMS template is true and dynamically add a CSS class?

In AnQiCMS template development, we often need to adjust the display style of the page based on the specific attributes of the content.This includes dynamically adding CSS classes based on the boolean value of custom fields (i.e., true or false status), thus achieving a more flexible and expressive interface.AnQiCMS with its flexible content model design allows users to create various custom fields for different content types (such as articles, products).These custom fields greatly enrich the expression of content, enabling templates to be highly customized for different business needs.###

2025-11-09

How to combine `if` and `yesno` filters in AnQiCMS templates to display different prompts based on VIP status and expiration time?

In website operations, providing differentiated services and content prompts to different user groups is a key link in improving user experience and achieving business goals.Especially on websites with a VIP membership system, displaying personalized information based on the user's VIP status and even the expiration time of the membership can greatly enhance the user's sense of belonging and willingness to interact.AnQiCMS (AnQiCMS) relies on its flexible template engine and rich tags, filters, making everything simple and efficient.Today, let's discuss how to use the AnQiCMS template

2025-11-09

How to ensure that the AnQiCMS template does not cause page rendering errors when the variable is `nil`?

When building a website with AnQiCMS, we often encounter the situation where template variables may be empty (`nil`).For example, a document may not have a thumbnail set or a custom field may not be filled in.If the template code does not properly handle these potential null values, errors may occur during page rendering, affecting user experience and even causing some website functions to be unavailable.Fortunately, the AnQiCMS template engine provides various mechanisms to help us elegantly handle the cases where variables are `nil`, ensuring the stability and smoothness of the page

2025-11-09

How can you get the document details of Anqi CMS by document ID?

When using AnQi CMS to manage website content, we often need to retrieve detailed information about specific documents from the backend, whether it is to display content on custom pages or integrate data into other systems (such as mini-programs, mobile applications, etc.).AnQi CMS provides a powerful and flexible API interface, one of the core functions of which is to obtain specific document details through the document ID.Today, let's dive deep into how to use the document ID to easily obtain the details of Anqi CMS documents, making your content operations more efficient and automated.### Core Steps

2025-11-09

How to get the details of a document through the document URL alias (`filename`)?

In AnQi CMS, the document URL alias (`filename`) is a very practical feature, which not only makes your website URL more friendly and improves search engine optimization (SEO) effect, but also provides great convenience in content acquisition.When you need to obtain detailed information about a specific document through programming, AnQiCMS provides a simple and intuitive API interface.### Core Feature Revelation: Get Details Using Document URL Alias To get all details of the document through its URL alias

2025-11-09

If both `id` and `filename` parameters are provided, which one will the AnQi CMS document detail interface prioritize?

In AnQi CMS, getting document details is a very frequent operation in our daily operation.We usually request document data through the unique numeric identifier `id` or the user-friendly URL alias `filename`.

2025-11-09

What error message will the interface return if the document does not exist when getting the document details?

In the daily operation and development of Anqi CMS, we often need to retrieve website content through API interfaces, among which the 'Get Document Detail Interface' (`/api/archive/detail`) is undoubtedly one of the most frequently used ones.This interface allows us to retrieve the details of a specific article or product by document ID or URL alias (filename).However, during use, we are bound to encounter such situations: When the requested document does not exist in the system, what kind of error message will the interface return?This is for front-end page display

2025-11-09