How to find the number of occurrences or the first occurrence position of a keyword in a string on a line in a template?

Calendar 👁️ 68

In Anqi CMS template design, sometimes we may need to analyze and display content more finely, such as finding the position of a specific keyword for the first time in a text or counting how many times it appears.These requirements are very useful in dynamic content display, information extraction, or辅助SEO.Benefiting from AnQi CMS adopting a template engine syntax similar to Django, we can take advantage of its powerful filter functions to achieve these goals.

Next, we will discuss how to use the built-inindexandcountfilter, efficiently complete these operations.

to find the first occurrence of a keyword:indexFilter

In AnQi CMS template, when we encounter the need to locate the first occurrence of a specific keyword in a text,indexThe filter is your reliable assistant. This filter will return the starting index of the first occurrence of the keyword in the string.

Usage:

indexThe basic syntax of the filter is very intuitive:

{{ 原始字符串变量|index:关键词 }}

Among them:

  • 原始字符串变量It is the text content you want to search for.
  • 关键词Is the substring you want to search for.

Interpretation of the returned result:

  • If the keyword is found in the original string,indexThe filter returns an integer representing the starting position of the first occurrence of the keyword. This position index is from0the calculation starts.
  • If the keyword is not found in the original string,indexThe filter will return-1.
  • It should be noted that when processing strings containing Chinese,indexThe filter considers a Chinese character to occupy 3 positions when calculating positions. For example, in the Chinese sentence '你好', the index position of '好' will be3.

Actual application example:

Assuming we have an article titlearticle.TitleThe content is "Welcome to AnQiCMS (AnQiCMS)". We want to know the position of the first occurrence of "CMS":

{% set articleTitle = "欢迎使用安企CMS(AnQiCMS)" %}
{% set firstIndex = articleTitle|index:"CMS" %}

<p>标题: {{ articleTitle }}</p>
<p>"CMS" 首次出现的位置在索引: {{ firstIndex }}</p>

{% if firstIndex != -1 %}
    <p>关键词已找到!</p>
{% else %}
    <p>关键词未找到。</p>
{% endif %}

The code will output:

标题: 欢迎使用安企CMS(AnQiCMS)
"CMS" 首次出现的位置在索引: 18

关键词已找到!

By usingindexThe result of the filter is with-1Comparing, we can easily determine if the keyword exists and display different content as needed.

Count the number of times the keyword appears:countFilter

If your requirement is to count the total number of times a keyword repeats in a string, thencountThe filter will perfectly meet your requirements. It will traverse the entire string, calculating the frequency of the specified keyword.

Usage:

countThe syntax of the filter is also simple and clear:

{{ 原始字符串变量|count:关键词 }}

Among them:

  • 原始字符串变量It is the text content you want to search for.
  • 关键词Is the substring you want to count the occurrence of.

Interpretation of the returned result:

  • countThe filter will return an integer representing the total number of times the keyword appears in the original string.
  • If the keyword is not found, it will return0.

Actual application example:

Continue using the article title you just used: 'Welcome to AnQiCMS (AnQiCMS), let's count how many times 'CMS' appears:

{% set articleTitle = "欢迎使用安企CMS(AnQiCMS)" %}
{% set occurrenceCount = articleTitle|count:"CMS" %}

<p>标题: {{ articleTitle }}</p>
<p>"CMS" 在标题中出现了: {{ occurrenceCount }} 次</p>

{% if occurrenceCount > 0 %}
    <p>关键词多次出现,可能是一个重要主题。</p>
{% else %}
    <p>关键词未在标题中出现。</p>
{% endif %}

The code will output:

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

关键词多次出现,可能是一个重要主题。

This feature is very useful in analyzing content density, detecting repeated words, or dynamically adjusting content display based on the frequency of specific keywords, and other aspects.

Advanced Applications and Precautions

Use with other filters

indexandcountThe filter is not only suitable for simple strings, but can also be used withsplitCombine filters to process array (also known as slice/slice) data. For example, first split a comma-separated string into an array, and then search for a specific element in the array:

{% set tagsString = "安企CMS,CMS模板,建站系统,CMS" %}
{% set tagsArray = tagsString|split:"," %}
{% set cmsCountInArray = tagsArray|count:"CMS" %}
{% set cmsIndexInArray = tagsArray|index:"CMS模板" %}

<p>标签列表: {{ tagsString }}</p>
<p>"CMS" 在数组中出现了: {{ cmsCountInArray }} 次 (注意:这里是完全匹配数组元素)</p>
<p>"CMS模板" 在数组中首次出现的位置: {{ cmsIndexInArray }}</p>

Case sensitive

Please note,indexandcountThe filter is when performing keyword matchingCase sensitiveThis means that 'cms' and 'CMS' will be considered as different keywords.If you need to perform a case-insensitive search, you can consider converting both the original string and the search keyword to uppercase or lowercase (for example, usinglowerorupperThe filter), then perform the operation.

{% set text = "AnQiCMS是一款优秀的CMS" %}
{% set keywordLower = "cms" %}

<p>原始文本: {{ text }}</p>
<p>查找 "cms" (区分大小写): {{ text|count:keywordLower }} 次</p>
<p>查找 "cms" (不区分大小写): {{ text|lower|count:keywordLower }} 次</p>

Applicable to different data types

  • String: indexandcountIt will find the substring in the string content.
  • Array/Slice: indexandcountChecks if the array contains an element with the keywordPerfect matchand returns its index or count. They do not perform substring matching.
  • For structured data such as objects or maps, if you need to determine whether a key name exists, you can usecontaina filter, but it does not directly provide an index or count.

Summary

In the AnQi CMS template,indexandcountThe filter provides us with powerful string analysis capabilities, whether you want to precisely locate keywords or count their frequency in the text, it can be easily achieved.Combine conditional judgment and loop template tags, these filters can help you build a more intelligent and dynamic website content display logic.In actual use, please pay attention to their case sensitivity and matching behavior under different data types to ensure the expected effect.


Frequently Asked Questions (FAQ)

Q1:indexandcountIs the filter case sensitive? A1:Yes,indexandcountThe filter is case-sensitive when searching for keywords. For example, searching for 'cms' and 'CMS' will yield different results.If you need to perform a case-insensitive search, you can first convert both the original string and the search keyword to uppercase or lowercase (for example, usinglowerThe filter), then perform the operation.

Q2:indexWhat does the number returned by the filter represent? What happens if the keyword is not found? A2: indexThe filter returns the starting position (index) of the first occurrence of the keyword in the string. This index is from0Start calculating. For example, if the keyword is the first character of the string, then its index is0. If the keyword is not found,indexwill return-1.

Q3: Can these filters be used for other data types besides strings? A3: countandindexThe filter is mainly used for strings and arrays (or what is called slices/slice). For arrays, they check if the keywords are ascomplete elementsexists within the array, not a partial match. If you need to determine whether a key name exists in an object or a mapping (map), you can consider usingcontainA filter that does not directly provide index or count statistics.

Related articles

How to split a string into an array or concatenate array elements into a single string in a template?

During the development of Anqi CMS templates, we often encounter situations where we need to process strings, such as converting a text segment separated by a specific symbol into a list, or concatenating multiple items in a list into a continuous text.The Anqi CMS template engine provides powerful filters (Filters) to help us easily implement these operations, greatly enhancing the flexibility of the template. ### AnQi CMS Template Engine Basics The AnQi CMS template engine syntax is designed to be very user-friendly, similar to the Django template engine.It is mainly through double curly brackets

2025-11-08

How to display the current year or a custom formatted current date and time in the template?

## In Anqi CMS template, flexibly display the current date and custom time format In website operations, we often need to display date and time information dynamically on the page, whether it is the current year in the copyright statement, the publication time of articles, or the countdown of activities.The AnQi CMS provides a very flexible and easy-to-use method to display the current year or a custom date and time format in templates, keeping your website content up to date and enhancing user experience.The Anqi CMS template system adopts syntax similar to the Django template engine, making the display of dynamic content intuitive

2025-11-08

How to use `{filename}` or `{catname}` in pseudo-static rules to generate SEO-friendly custom URLs for articles, categories, and single pages?

In website operation, generating SEO-friendly URL addresses for content is a key link to improving website SEO performance.A clear, keyword-rich URL not only makes the page content easy for users to understand, but also helps search engines better understand and crawl web pages.AnQiCMS provides powerful custom static rule functionality, allowing us to flexibly use variables such as `{filename}` and `{catname}` to generate highly customized URLs for articles, categories, and even single pages.### Optimize URL

2025-11-08

How to set up image resource management in AnQi CMS and support batch regeneration of thumbnails in different sizes?

In website operation, images are not only an important part of the content, but also a key factor affecting page loading speed and user experience.Efficient image management can greatly enhance the performance and maintainability of a website.AnQiCMS (AnQiCMS) is well-versed in this field, providing users with comprehensive image resource management functions, especially excelling in thumbnail settings and batch processing, making image operations more convenient and flexible.### Core Feature Overview: AnqiCMS Image Management System AnqiCMS Image Resource Center is a collection of upload, classification, editing

2025-11-08

How to safely escape HTML code in a template to prevent XSS attacks, or force non-escaping of HTML content?

When building a website, ensuring the security of the content, especially the prevention of cross-site scripting (XSS) attacks, is a crucial aspect.AnQiCMS (AnQiCMS) provides powerful tools at the template level to manage the escaping of HTML content, thereby effectively protecting the website and its users.Understanding how to safely handle HTML code in templates is essential knowledge for every AnQi CMS user when performing content operations and template development.### Default security mechanism of AnQi CMS template The template engine of AnQi CMS adopts a design philosophy similar to Django

2025-11-08

How to determine if a string or array contains a specific keyword in a template?

In the template development of Anqi CMS, we often need to dynamically adjust the page display based on specific attributes or text fragments of the content.Determine whether a string or array contains a specific keyword is a key step in implementing this dynamic logic.AnQiCMS is a powerful Django style template engine with built-in filters, making this operation very intuitive and efficient.## Core Tool: `contain` Filter The most direct way in AnQiCMS template system is

2025-11-08

How does AnQi CMS ensure that articles are automatically displayed on the website front end at the specified time?

In the fast-paced digital content world, how to ensure that content is accurately delivered to the target audience at the right time is a challenge faced by every content operator.Manual operation is not only inefficient but may also lead to release errors due to negligence.The timed release function of AnQiCMS (AnQiCMS) is specifically designed to address this pain point, providing an intelligent and automated way to ensure that your articles are displayed accurately on the website front end at the preset time points.### Understanding the core value of scheduled publishing For content operators, scheduled publishing is not just a convenient tool

2025-11-08

How to display different language versions and content on the front-end of a website through a language switcher based on user selection?

AnQi CMS is an efficient and customizable content management system that excels in multilingual support, allowing operators to easily build multilingual websites for global users.By cleverly utilizing its built-in features, we can build a flexible language switcher on the website front-end, accurately presenting different language versions of content based on user preferences, thereby effectively enhancing user experience and expanding market coverage.### Understanding the Core of Multilingual Support Implementing multilingual support in Anqi CMS is not just a simple text replacement, but a systematic workflow.

2025-11-08