How to calculate the total number of occurrences of a specific value in an array in AnQiCMS?

Calendar 👁️ 56

In website operation, we often need to deal with various data, one of the common needs is to count the number of times a specific value appears in a dataset.For example, you might want to know how many times a keyword appears in an article, or how many colors of a product are marked as 'hot'.For users of AnQiCMS, the system's powerful template engine provides a very convenient tool to complete this task.

The AnQi CMS template engine is powerful and flexible, it comes with a variety of filters (Filters) that can help us easily process and format data. To count the total number of times a specific value appears in an array, we need to use one namedcount.

UnderstandcountFilter

countThe filter is a function specifically used for counting in the Anqi CMS template engine. Whether you want to count the frequency of a keyword in a line of string or calculate the number of times a specific element appears in an array (slice),countFilters can always be used. It will return an integer indicating the total number of times the value you are looking for appears in the target data.

How to use in the templatecountFilter

UsecountFilters are very intuitive. The basic syntax is:

{{ 您的数组或字符串 | count: "要查找的值" }}

Let's look at several actual examples to see how it works.

Scenario one: Count the number of times a keyword appears in a string.

Assuming you have a piece of text content and want to know how many times a certain keyword is mentioned, this is very useful in SEO content optimization or content quality checks.

For example, we have an introduction about Anqi CMS and want to count how many times the word 'CMS' appears:

{% set description = "安企CMS是一个高效、可定制的内容管理系统,它支持多站点管理,灵活的内容模型,以及强大的SEO工具。安企CMS致力于为中小企业提供优质CMS服务。" %}
<div>
    “CMS”在这个描述中出现了:{{ description | count: "CMS" }} 次。
</div>

After running this template code, the page will display:

“CMS”在这个描述中出现了:3 次。

As you can see,countThe filter accurately identifies and counts all occurrences of "CMS" in the string.

Example scenario two: Count the number of occurrences of a specific value in the array.

In Anqi CMS, many data exist in array form, such as througharchiveDetaillabel to get the document image listImagesor the checkbox fields defined in the custom content model, etc.

Assuming your content model has a field namedfeatureswhich includes multiple tags such as["多语言","SEO优化","响应式","多语言","可定制"]. How many times was the 'Multilingual' tag selected?

First, we need to get this array. Iffeaturesis a custom field, you can get it like this:

{% archiveDetail myFeatures with name="features" %}
{% set featureList = myFeatures | list %} {# 假设myFeatures是字符串形式的JSON数组,用|list过滤器转成实际的数组 #}
{# 如果myFeatures已经是Go原生的slice/array类型,则无需|list转换 #}

<div>
    在功能列表中,“多语言”标签出现了:{{ featureList | count: "多语言" }} 次。
</div>

To demonstrate more intuitively, we can also define an array directly in the template:

{% set tags = '["多语言","SEO优化","响应式","多语言","可定制"]' | list %}
<div>
    在标签列表中,“多语言”标签出现了:{{ tags | count: "多语言" }} 次。
</div>

Run this code, and the page will display:

在标签列表中,“多语言”标签出现了:2 次。

This indicatescountThe filter can also accurately count the number of occurrences of specific elements in the array.

Important notes

While usingcountWhen filtering, there are several details that are worth noting:

  • The principle of exact match:countThe filter strictly requires that the value to be searched for matches the elements or substrings in the target data exactly during statistics.This means that if an element in the array is "Multilingual (English)", and you are looking for "Multilingual", it will not be counted.
  • Case sensitive: Generally speaking,countThe filter is case sensitive. For example, when searching for "cms", it will not include "CMS".Make sure the value you are looking for matches the actual value in the target data case by case.

Summary

Of Security CMScountThe filter is a simple and powerful tool that can help you easily count the number of occurrences of specific values in strings and arrays in website templates.This simplifies the logic of data analysis and also allows content operations personnel to handle and display data more flexibly, thereby optimizing website content and user experience.These practical template tags and filters indeed provide us with an efficient and customizable content management solution for Anqi CMS.


Frequently Asked Questions (FAQ)

Q1:countIs the filter case sensitive?

A1: Yes,countThe filter is usually case sensitive. This means that if you search for "Apple", it will not count "apple" or "APPLE."}To perform case-insensitive statistics, you may need to convert the target string or array elements to uppercase or lowercase first (along with other filters, such aslowerorupper), then count.

Q2: Besides,countFilter, what other filters are available in AnQi CMS for array operations?

A2: AnQi CMS template engine provides a rich set of array operation filters. In addition,countAlso commonly used:

  • length: Get the length of the array (number of elements).
  • contain: Check if the array contains a specific value, returntrueorfalse.
  • joinJoin array elements into a string with a specified delimiter.
  • splitSplit a string into an array with a specified delimiter.
  • firstandlast: Retrieve the first and last elements of the array.
  • slice: Slice elements from the array within a specified range.

Q3: If the data I want to find is in a multi-dimensional array,countCan the filter still be used?

A3: countThe filter currently targets direct counting of one-dimensional strings or arrays. If your data is a multi-dimensional array (for example, each element of an array is another array),countThe filter cannot be directly applied to all nested levels. You may need to combineforLooping and conditional judgment, traversing the array layer by layer, or preprocessing the data on the backend before it is sent into the template, flattening it into a one-dimensional array and then counting it.

Related articles

How to count the frequency of a keyword in a string in the AnQiCMS template?

In content operation, we often need to process and analyze text.This may involve checking keyword density to optimize search engine rankings, or it may just be to understand the frequency of a specific word appearing in the content in order to better assess the focus of the content.AnQiCMS (AnQiCMS) boasts its high efficiency and customizable features, providing users with powerful content management capabilities, and its flexible template system makes it easy for us to handle various content display needs.Today, let's talk about a very practical feature: how to count the number of times a keyword appears in a string in a template

2025-11-08

How to utilize the multi-site feature of Anqi CMS to achieve unified or differentiated display of content between different sites?

The multi-site feature of AnQi CMS is an extremely powerful feature, which provides unprecedented flexibility for website operators, whether it is managing multiple independent brand websites or building a content-sharing matrix, they can handle it with ease.The core of this feature lies in the fact that it allows you to efficiently manage and display multiple independently operated websites under a single secure CMS system, and cleverly balances content differentiation and unity.### Understanding the multi-site capability of AnQi CMS Firstly, we need to clarify the operation mode of the multi-site function of AnQi CMS

2025-11-08

How can you implement a unique display style for content under a specific category in AnQi CMS?

In website operation, we often encounter such needs: a particular content category needs a unique display style to highlight the importance, uniqueness, or brand character of its content.For example, your 'news center' may require a concise list layout, while 'selected cases' may require a more visually striking grid layout or slideshow display.AnQiCMS provides powerful template customization capabilities, making it intuitive and efficient to achieve this goal.Why do you need to customize the display style for a specific category?A unified website style is indeed important

2025-11-08

What ways does AnQi CMS support to individually present the detailed content of a single document?

When using AnQi CMS to manage website content, if you want each document's detailed content to be presented in a unique and eye-catching way, the system provides very flexible customization settings.This is not just about changing the text color or font size, but also about deep customization from content structure to display form.Firstly, the foundation of personalized display lies in **content model and custom fields**.Our AnQi CMS allows us to create different content models based on actual business needs, such as 'articles', 'products', 'news', and even 'cases'.

2025-11-08

What are the practices when using the `count` filter to calculate keyword density?

In website content operation, the reasonable use of keywords is an important factor in improving search engine visibility.We not only need to ensure that the core keywords are reflected in the content, but also need to pay attention to their frequency of occurrence, avoiding overloading or underusing.AnQiCMS provides a variety of powerful content management tools, among which the `count` filter is a very practical feature that can help us effectively count the number of occurrences of keywords in articles.###

2025-11-08

How to judge whether a line of text in the AnQiCMS template contains a certain keyword?

In website operation, we often encounter such needs: to decide how to display page elements based on whether the content contains a specific word, such as highlighting some text, or only displaying a module when certain conditions are met.The AnQiCMS template system provides flexible filter functions to help us easily implement these keyword-based judgments.This article will delve into how to efficiently and accurately determine whether a line of text in the AnQiCMS template contains a certain keyword.### Use `contain`

2025-11-08

How to check if a specific element exists in an array within a template

In the daily operation and template customization of AnQi CMS, we often encounter situations where we need to dynamically adjust the display of the page according to the data content.One common and practical requirement is to determine whether a specific element exists in an array (or list) within a template.This is crucial for realizing personalized recommendations, conditional content display, and even for functions such as permission control.The Anqi CMS adopts a template engine syntax similar to Django, providing rich tags and filters to handle data.When we get some data set from the backend, such as the list of article tags

2025-11-08

What role can the `contain` filter play in the context of sensitive word filtering?

In today's era where content is king, website operators are facing the dual challenge of actively publishing high-quality content while strictly controlling content security and compliance.Especially on platforms where user-generated content is increasing, how to efficiently and accurately filter sensitive words has become a key link in maintaining a healthy website ecosystem and protecting brand reputation.AnQiCMS (AnQiCMS) fully understands this need and provides many content security management functions, among which the `contain` filter can play a surprisingly practical role in the sensitive word filtering scenario.### The Foundation of Content Security

2025-11-08