How to find the first occurrence index of a character or substring in the AnQiCMS template?

Calendar 👁️ 71

During website content display or template development, we often encounter situations where we need to process specific text, such as checking for the existence of a keyword or locating the first occurrence of a character or substring.The template engine of AnQiCMS (AnQiCMS) provides a series of powerful filters (Filters) to help us complete these tasks efficiently.Today, let's discuss how to useindexA filter that accurately finds the index of the first occurrence of a character or substring in the AnQiCMS template.

UnderstandingindexFilter

The AnQiCMS template engine provides a namedindexThe built-in filter that is specifically used to solve the problem of locating the position of characters or substrings.This filter helps us quickly find the starting index of the first occurrence of a character or substring in a given text (string or array).

Its basic usage is very intuitive:{{ obj|index:"关键词" }}

Among them:

  • objRepresents the string or array you want to search for.
  • "关键词"Is the character or substring you want to find.

IfindexThe filter successfully found the keyword, it will return the starting index of the first occurrence of the keyword, which is from0counting from. If the keyword does not exist inobj, it will return-1.

In actual use, special attention must be paid to the handling of Chinese characters.The AnQiCMS template engine calculates string indices based on bytes rather than character length.This means that a Chinese character usually occupies multiple bytes (for example, it may occupy 3 bytes under UTF-8 encoding), which affectsindexThe filter returns the index value. Therefore, when processing text containing Chinese characters, please make logical judgments based on the understanding of byte length.

Actual application scenarios and examples

Scenario one: Find the first occurrence position of a substring in ordinary text

Suppose we have a text introducing Anqi CMS, we want to know where the substring "CMS" first appears.

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

The output of this code will be18. Let's simply analyze this index value:

  • //使///Each Chinese character occupies 3 bytes. Therefore, the first six Chinese characters total6 * 3 = 18bytes.
  • C: The following English characterCThe index is18. So,indexThe filter returns18It is consistent with the logic of byte counting.

Scene two: cooperation{% set %}Make a conditional judgment.

In template development, we usually do not display the index value directly to the user, but use this index to drive some logical judgments, such as displaying or hiding an element based on whether a substring exists.

{% set page_content = "AnQiCMS 是一个高效的内容管理系统,深受用户喜爱。" %}
{% set keyword_position = page_content|index:"高效" %}

{% if keyword_position != -1 %}
    <p>内容中提到了“高效”这个词!</p>
{% else %}
    <p>内容中未发现“高效”这个词。</p>
{% endif %}

This code will checkpage_contentDoes it contain the words 'efficient'? As 'efficient' does exist,keyword_positionit will not be equal to-1Therefore, the page will display 'The word 'efficient' was mentioned in the content'!. This way, the template can dynamically adjust the display according to the content.

Scenario three: Finding the first occurrence of an element in an array

indexThe filter is not only applicable to strings but can also be used to find the first occurrence of a specific element in an array.

{% set categories = ["网站新闻", "产品介绍", "技术文章", "产品介绍"] %}
{{ categories|index:"产品介绍" }}

The output of this code will be1In the array,indexThe filter returns the index position of the target element in the array, starting from0Start counting. It will only return the first occurrence, even if there are multiple identical elements in the array.

What are the precautions

  1. Return the first occurrence: indexThe filter always returns the position of the first occurrence of the keyword. If you need to get all occurrences, this goes beyondindexThe range of filter capabilities may require more complex template logic or processing before content is stored.
  2. Case sensitive:String matching is typically case-sensitive. For example, searching forcmsandCMSThe result may vary.
  3. Return-1Meaning:Make good use of-1This return value is used to determine if a keyword does not exist, which is very useful when building conditional logic.

ByindexFilter, we can easily perform precise text positioning in the AnQiCMS template, thereby realizing a more flexible and intelligent content display strategy.


Frequently Asked Questions (FAQ)

Q1:indexDoes the filter support regular expression search? A1: indexThe filter does not support regular expressions. It performs an exact match search on plain strings or array elements.If you need to perform more complex matching based on regular expressions, you may need to consider preprocessing at the content management or program level before passing the processed data to the template.

Q2: How to determine if a string contains another substring without knowing the specific position? A2: If you just want to check for existence and not need to know the specific location, the AnQiCMS template engine providescontaina filter. For example:{% if "欢迎使用安企CMS"|contain:"CMS" %} 包含 {% else %} 不包含 {% endif %}This will return a boolean value (True or False), more concise and clear.

Q3:indexThe index value returned by the filter is based on characters or bytes? How can we accurately determine the index if the string contains both Chinese and English? A3: indexThe filter returns the index based onbytesThe. As mentioned in the article, Chinese characters usually occupy multiple bytes (such as 3 bytes) in UTF-8 encoding, while English characters occupy 1 byte.Therefore, in a string containing mixed Chinese and English characters, it is necessary to calculate and understand the index value according to the byte length of the character encoding.For example, if a Chinese character is inindexThe result has moved forward by 3 units, so the index of the next character (whether Chinese or English) will start counting from these 3 units.

Related articles

How to extract specific number information from a long numeric string in AnQiCMS template?

In website operations, we often encounter scenarios where we need to handle some structured long numeric string.For example, a product code may contain the production date and batch information; an order number may imply regional codes and serial numbers; or may be a unique identifier generated by specific business logic.These long digital strings often carry rich metadata, and we may only need the numerical information at specific positions for display, filtering, or further processing.

2025-11-08

How to precisely control the display of floating-point numbers in the AnQiCMS template, such as retaining two decimal places?

In website content operation, the way numbers are presented often affects user experience and the accuracy of information.Especially for floating-point numbers, such as product prices, statistics, and ratings, it is common to require accuracy to several decimal places or rounding according to business needs.AnQiCMS is a powerful template system that provides us with a flexible way to handle these data.Today, let's delve into how to efficiently and accurately control the display of floating-point numbers in the AnQiCMS template.

2025-11-08

How to split a line of text content (such as a tag string) into an array of individual words for processing in AnQiCMS?

In the practice of AnQiCMS content management, we often encounter scenarios where it is necessary to split a seemingly simple line of text into smaller, more independent 'words' for fine-grained processing.For example, the document tag (Tag), keyword list, or multiple values separated by a specific symbol in custom fields.The core of this requirement lies in converting a string into an array that can be traversed and manipulated individually.

2025-11-08

The `escape` and `escapejs` filters in AnQiCMS are applicable to which HTML/JS escaping scenarios?

In AnQiCMS template development, it is very important to understand and properly use escape filters to ensure website security and correct content display.The system uses a template engine syntax similar to Django, which means it takes some security measures by default when handling variable output.Today, let's talk about the `escape` and `escapejs` filters to see in which scenarios they can be used.

2025-11-08

In AnQiCMS template, how to convert a string number into an actual `integer` or `float` type?

When working with the Anqi CMS template to display content and make logical judgments, we often encounter situations where we need to perform operations on numbers.However, data obtained from a database or content model, even if it looks like a number in the background, is sometimes passed as a string (``string``) at the template level.If this is directly performed arithmetic operations or numerical comparisons, unexpected results may occur.

2025-11-08

How to concatenate the tag array in AnQiCMS template into a string with a custom delimiter?

In AnQiCMS template development, we often need to display a set of data obtained from the database, such as the multiple tags (Tags) of articles, in a user-friendly manner rather than simply listing them.One of the most common needs is to concatenate these tags into a string with a custom separator, such as AnQiCMS's powerful template engine provides a flexible way to achieve this goal.

2025-11-08

How to get the total length of elements in a string, array, or key-value pair in AnQiCMS template?

In AnQi CMS template design, dynamically obtaining the total length of elements in a string, array, or key-value pair is a very practical feature. It can help us flexibly display information on the page, such as showing the number of products, the number of comments, or adjusting the layout according to the content length.The Anqi CMS template engine provides simple and efficient filters to meet these requirements.### Core Tool: `length` Filter The most direct and universal method to obtain the total number of elements in any string, array (slice), or key-value pair (map/struct) is to use

2025-11-08

How does the AnQiCMS template automatically convert line breaks in text to HTML tags such as `<p>` or `<br>`?

In website content presentation, text formatting is often the key to determining the user's reading experience.We often encounter such needs: the text content obtained from the background database usually only contains simple newline characters (`\n`), and if it is displayed directly on the web page, the browser will not intelligently convert these newline characters into the HTML paragraph (`<p>`) or line break (`<br>`) tags we expect, causing the content to be cramped together and lose its original structure and readability.AnQiCMS (AnQiCMS) has fully considered this point in template design

2025-11-08