How does the `count` filter count the occurrences of a specific keyword in a string or array?

Calendar 👁️ 69

In AnQi CMS template development, efficiently handling and analyzing content is the key to improving website interactivity and information display capabilities.Sometimes, we need to know how many times a specific word appears in a text or how many times a specific element is included in a data list.countThe filter can be put to good use. It is a very practical tool that can help us quickly count the occurrences of a specific keyword in a string or an array (slice).

Core Function Overview

countThe main function of the filter is to calculate the total number of times a specified keyword appears in a given string or array.It provides a concise and efficient way to perform preliminary quantitative analysis, which is particularly convenient in scenarios where content analysis, data verification, or conditional rendering is required.

Use Case 1: Count the frequency of a keyword in a string

When you have a piece of text and want to know the frequency of a specific word in it,countThe filter can directly process string data.

The usage is very intuitive, just pass the string variable through a pipe symbol.|pass tocountFilter, and specify the keyword you want to count after the colon.:You can specify the keyword you want to count after the colon.

For example, we have a piece of text: “Welcome to AnQiCMS (AnQiCMS)”, now we want to know how many times the word “CMS” appears in this text:

{{"欢迎使用安企CMS(AnQiCMS)"|count:"CMS"}}

Run this code and the output will be2This is becausecountThe filter successfully identified and counted the two occurrences of "CMS" in the string.This feature is very useful for content editing to perform keyword density analysis, for SEO optimization personnel to check keyword layout, or for any scenario that requires quantitative analysis of text.

Use case two: Count the occurrences of a specific element in an array (Slice)

countThe filter can not only handle strings but also be applied to arrays (usually referred to as slice in AnQiCMS templates). However, there is an important detail to pay special attention to when counting arrays:The keyword must match the elements in the array exactly, does not support partial matchingThis means that if you want to count an element in an array, the keyword you provide must match the entire value of the element in the array.

Let us understand this through a specific example. Suppose we have a byfieldsThe filter from the array split from the string "splits the string 安企CMS"valuesIt contains["splits", "the", "string", "安企CMS"].

If we want to count the number of times the element "the" appears:

{% set values = "splits the string 安企CMS"|fields %}
{{values|count:"the"}}

This code will output correctly1because there is an element in the array that matches "the" exactly.

However, if we try to count the occurrences of '安企':

{% set values = "splits the string 安企CMS"|fields %}
{{values|count:"安企"}}

The output result will be:0This is because one element of the array is "AnQi CMS", and the keyword "AnQi" we provided is only a part of this element, not a complete match. When usingcountRemember this 'exact match' rule when filtering and counting an array to avoid unexpected results.

Usage method

Whether you are counting strings or arrays,countThe basic syntax pattern of the filter is consistent:

{{ obj|count:关键词 }}

Among themobjRepresents the string variable or array variable you want to operate on,关键词which is the specific text or number you want to count the occurrences of.

Example Demonstration

Here are some more comprehensive examplescountExample of filter usage to help you better understand and apply:

{# 统计字符串中关键词出现的次数 #}
{{"欢迎使用安企CMS(AnQiCMS)"|count:"CMS"}}
{# 预期输出: 2 #}

{# 统计数组中特定元素出现的次数(完全匹配)#}
{% set values = "splits the string 安企CMS"|fields %}
{{values|count:"the"}}
{# 预期输出: 1 #}

{# 统计数组中特定元素出现的次数(非完全匹配,结果为0)#}
{% set values = "splits the string 安企CMS"|fields %}
{{values|count:"安企"}}
{# 预期输出: 0 #}

{# 另一个数组完全匹配的例子 #}
{% set tags = ["安企CMS", "网站运营", "Go语言", "安企CMS"] %}
{{tags|count:"安企CMS"}}
{# 预期输出: 2 #}

{# 统计字符串中大小写敏感的关键词 #}
{{"AnQiCMS is a great CMS."|count:"cms"}}
{# 预期输出: 1 (安企CMS模板在字符串统计时默认区分大小写) #}

{# 统计数字在数字数组中的出现次数 #}
{% set numbers = "[1, 5, 2, 5, 3]"|list %}
{{numbers|count:"5"}}
{# 预期输出: 2 (这里关键词5需作为字符串传入,或者系统会尝试转换为字符串进行匹配) #}

Through these examples, we can seecountHow to apply the filter in different scenarios and understand its 'perfect match' feature when processing arrays. Flexibly apply it in your Safe CMS project development and content operationcountThe filter can bring you more accurate data insights and more efficient template control.


Frequently Asked Questions (FAQ)

  1. Q:countDoes the filter distinguish between uppercase and lowercase when counting strings?A: Yes,countThe filter is case-sensitive when counting keywords in a string.For example, "CMS" and "cms" are considered different keywords for statistics.countUse it first beforelowerorupperThe filter converts strings to uppercase or lowercase and then performs the count.

  2. Q: Why am I getting a count of 0 for a keyword in an array when I'm sure it exists in the array elements?A: This is likely because the keywords you provided do not match the elements in the array completely.countThe filter requires the keyword to be exactly consistent with the value of the array element when counting in the array.Please check if your keywords include extra spaces, punctuation marks, or if they are just part of the array element value.If the array element is of numeric type, the keyword passed in should also try to convert it to a numeric type, or ensure that both types are consistent.

  3. Q:countCan the filter count keywords in nested arrays or nested objects?A: According to the current document description,countThe filter is mainly used to count keywords in flat strings or one-dimensional arrays.It does not directly support deep recursive statistics of nested arrays or complex objects.forLoops and conditional judgments are used to implement more complex logic in the template.

Related articles

The `contain` filter how to determine if a string or array contains a specified keyword?

In Anqi CMS template development, flexibly controlling the display of content is the key to improving website user experience and operational efficiency.Sometimes, we may need to determine whether a piece of text, a list (array), or a data object (Map/Struct) contains a specific keyword or property.At this time, the `contain` filter provided by Anqi CMS can give full play to its role, it can help us easily achieve this kind of conditional judgment, making the template logic more intelligent.What is the `contain` filter?

2025-11-07

How `length` and `length_is` filters are used to check the length of a string, array, or map?

In Anqi CMS template development, flexible handling and displaying data is the key to improving website interactivity and user experience.Understanding how to efficiently detect the length of strings, arrays, or mappings (similar to dictionaries or associative arrays in other programming languages) is the foundation for content operations and template customization.This article will introduce in detail the `length` and `length_is` practical filters in the Anqi CMS template engine, which will help you better control the display of page content.### `length` filter

2025-11-07

How `default` and `default_if_none` filters set a default display value for possibly empty variables?

In website content management, we often encounter situations where variable values may be empty.These empty values, if displayed directly on the front-end page, may lead to incomplete content display, page layout disorder, and even a bad user experience.AnQiCMS (AnQiCMS) as a powerful content management system, the Django template engine syntax it adopts provides us with a flexible way to handle such issues.

2025-11-07

How does the `add` filter work for adding numbers or concatenating strings in templates?

In AnQi CMS template design, we often need to perform some simple data processing, such as adding several numbers to display the total sum, or combining different text fragments into a complete sentence.At this time, the `add` filter is particularly convenient, as it is like a universal connector, capable of handling everything from arithmetic operations on numbers to the combination of text, making your template more flexible and dynamic.

2025-11-07

How does the `stringformat` filter output values of different data types in a custom format?

In the AnQiCMS template, mastering the format of data output is the key to content presentation.In order to display various data types (whether it is numbers, text, or more complex structures) in the way you expect to your visitors, AnQiCMS provides a powerful and practical tool - the `stringformat` filter.It is like a precise converter that can convert different types of values according to the rules you define, outputting neat and uniform strings.### Deep Understanding of `stringformat`

2025-11-07

How does the `thumb` filter quickly generate and display a thumbnail version of the original image URL?

In website operation, images are key elements to attract users and enrich content, but large image files often slow down page loading speed, affecting user experience and search engine optimization.Anqi CMS knows this and therefore provides a very convenient and efficient solution——the `thumb` filter.It can easily convert the original image into a thumbnail version suitable for web display, without manual processing, greatly enhancing the efficiency of content publication and the overall performance of the website.### Core Function Analysis: `thumb` Filter's Working Principle This is named

2025-11-07

How does AnQiCMS adaptively display website content for different devices (PC/Mobile end)?

In today's parallel network environment of multiple devices, users may access websites through desktop computers, laptops, tablets, or smartphones.Therefore, ensuring that the website content displays well on different devices and provides a smooth user experience is a key link in the success of website operation.AnQiCMS as an enterprise-level content management system fully considers this requirement and provides a flexible and diverse adaptive display scheme for device content, allowing users to choose the most suitable method according to their own situation.AnQiCMS mainly provides three core strategies for handling multi-device display of website content

2025-11-07

How to customize the display of SEO titles, keywords, and descriptions on the AnQiCMS homepage?

In the digital age, the homepage of a website is like the 'front door' of a company, the information presented to search engines is crucial.An meticulously optimized homepage that clearly conveys the core value of the website, attracts target users, and provides friendly crawling signals to search engines.In AnQiCMS, customizing the display of the SEO title (Title), keywords (Keywords), and description (Description) on the homepage is a straightforward and powerful process, which is an important manifestation of AnQiCMS's SEO-friendly features.

2025-11-07