How does the `index` filter find the first occurrence of a keyword in a string or array?

Calendar 👁️ 80

In AnQi CMS template development, we often need to finely control the content displayed, which includes flexible handling of string and array content.Understand and make good use of the various template filters provided by Anqi CMS, which can greatly enhance our ability to build dynamic and intelligent websites.Today, let's delve deeply into a very practical filter -indexIt can help us accurately locate the first occurrence of a keyword in a string or array.

indexFilter: The tool for accurately locating keywords

Imagine that you might need to adjust the display style based on whether the content of the article contains specific sensitive words, or when handling dynamically generated data lists, you need to know whether a specific value exists in the list, or even know its specific position in the list.indexThe filter is designed for these scenarios, it can help us find the starting position of the first occurrence of a specified keyword in a target string or array.

indexThe principle of the filter.

indexThe filter takes two parameters: one is the one to be searched forthe target(which can be a string or an array), and the other isKeywords(the content you want to find). Its return result is an integer:

  • If the keyword is found, it will return the starting position of the first occurrence of the keyword (counting from 0).
  • If the keyword is not found, it will return-1.

How to useindexFilter

indexThe basic usage syntax of the filter is very intuitive:

{{ obj|index:关键词 }}

HereobjIt can be a string containing text or an array (slice) that stores multiple values.关键词That is what you want to beobjsearched for the specific text or numeric value.

Example 1: Find a keyword in a string

Assuming we have a welcome string: 'Welcome to AnQiCMS (AnQiCMS)', we want to know where the word 'CMS' first appears.

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

Run this template code and the output will be18.

You might be curious, why not 6 or another number?This is because at the bottom of AnQi CMS, string processing is based on UTF-8 encoding byte calculations.A Chinese character usually occupies 3 bytes. Therefore, the five characters in "Welcome to AnQi" occupy 15 bytes, plus 1 byte for a space, followed by "CMS", so its starting byte position is 15 (Welcome to AnQi) + 3 (space) = 18.This is very important for accurately calculating the position of Chinese content.

Example two: Find an element in an array

indexThe filter also applies to arrays. Suppose we have a throughfieldsThe filter splits the string into an array:["splits", "the", "string", "安企CMS"]We want to find the position of the element "the".

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

This code will output1. In an array, the position also starts from 0, so 'splits' is at position 0, 'the' is at position 1. It is important to note that when searching in an array, }indexThe filter requires that the keyword matches the elements in the array exactly.

Example three: The keyword is not found.

IfindexThe filter could not find the specified keyword in the target, it will return a special value-1This is very useful in conditional judgments, for example:

{% set content = "这是一个关于网站运营的文章" %}
{% set position = content|index:"安企CMS" %}

{% if position != -1 %}
    <p>内容中包含了“安企CMS”,位置在:{{ position }}</p>
{% else %}
    <p>内容中没有找到“安企CMS”。</p>
{% endif %}

This code will output 'The content does not contain 'AnQi CMS', because 'AnQi CMS' does not appear in the given string.'

UseindexImportant considerations for the filter

  • The first occurrence position: indexThe filter will only return the first occurrence position of the keyword. If the same keyword appears multiple times in a string or array, it will not return all positions.
  • Special processing of Chinese characters:As explained in the string example, a Chinese character is inindexThe filter calculates the position and is considered to occupy 3 bytes of space. This is a detail that template developers for Chinese websites need to pay special attention to.
  • Exact match in the array:While usingindexThe filter searches for array elements and requires the keyword to match exactly with some element in the array. Partial matches are invalid.
  • Case sensitive: indexThe filter is case-sensitive when searching for keywords. For example, searching for 'CMS' and 'cms' will yield different results.

Summary

indexThe filter is a powerful and flexible tool in the Anqi CMS template, which can help us accurately locate the first occurrence of a keyword, whether it is dealing with strings or arrays.By understanding its working principles and usage precautions, we can write more intelligent and responsive templates to better control the display and interactive logic of website content.


Frequently Asked Questions (FAQ)

1.indexIs the filter case-sensitive?

Yes,indexThe filter is case-sensitive when searching for keywords. For example, searching for "cms" in the string "AnQiCMS" will return -1 because it cannot find an exact match for "cms".You need to make sure that the search keywords match the case of the text in the target.

2. BesidesindexFilter, what similar features does the Anqi CMS have to determine if text contains a keyword?

If you just want to check if a string or array contains a certain keyword without needing to know the specific position, you can usecontaina filter. It will directly return a boolean value (TrueorFalse),Use it more concisely, for example:{{"欢迎使用安企CMS"|contain:"安企CMS"}}.

3. Why is the position of 'CMS' in the Chinese '安企CMS' 18 instead of other numbers?

This is because Anqi CMS is developed based on Go language, and Go language will perform byte calculation based on UTF-8 encoding when processing strings.A Chinese character (such as '欢', '迎' etc.) usually occupies 3 bytes. Therefore,indexThe filter returns the starting byte position of the keyword in the string, not the character position that we usually understand visually.When truncating or locating a string, you need to consider the length of this byte.

Related articles

How does the `get_digit` filter retrieve a digit from a number at a specified position?

In the AnQi CMS template world, flexible handling and displaying data is a key link in content operation.When faced with the need to accurately extract a specific digit from a sequence of numbers, the `get_digit` filter is a very practical tool.It can help us achieve some detailed display requirements, such as grouping or highlighting based on the specific position of numbers. ### Core Function and Usage The main function of the `get_digit` filter, as the name implies, is to obtain a single digit from a number at a specific position.

2025-11-08

How to precisely control the decimal place display of floating-point numbers using the `floatformat` filter, including positive and negative digit settings?

In website content operations, accurately displaying numbers, especially floating-point numbers, is often a key factor affecting user experience and data professionalism.It is crucial to ensure that numbers are presented consistently and legibly in product prices, statistical data, or scientific reports.AnQiCMS (AnQiCMS) is well aware of this need, providing a powerful `floatformat` filter in the template engine to allow content creators to flexibly control the display precision of floating-point numbers.### `floatformat` filter

2025-11-08

How do the `first` and `last` filters get the first or last element of a string or array?

In AnQi CMS template development, in order to display content more efficiently and flexibly, we often use various filters to process the data.These filters are like various tools in a toolbox that can help us quickly format, cut, or extract data.Today, let's talk about two very practical and intuitive filters: `first` and `last`, and how they help us easily obtain the first or last element of a string or array.### 1. Getting to know the `first` and `last` filters Imagine that

2025-11-08

How does the `fields` filter split a single line string into an array of strings?

During the template development process of AnQi CMS, flexibly handling and displaying data is the key to improving website functionality and user experience.Sometimes, the content we receive from the backend may be a single line string containing multiple pieces of information, such as a list of keywords, product tags, or a set of feature descriptions.If we need to treat this information as separate elements for processing or display, for example, as a list, we would need a method to split this single string into multiple independent items.At this time, the `fields` filter provided by the Anqi CMS template engine can come into play.

2025-11-08

How do the `integer` and `float` filters convert strings to integers or floating-point numbers and handle conversion failure situations?

In web template development, flexible handling of data types is the key to ensuring correct content display.We often encounter situations where we need to convert string data obtained from databases or external interfaces into numbers for calculation or formatting display.AnQiCMS (AnQiCMS) fully considers this requirement, providing two built-in filters `integer` and `float` to help users easily convert strings to integers or floating-point numbers, and intelligently handle conversion failure cases, thereby enhancing the robustness of the template.

2025-11-08

How does the `join` filter concatenate elements of an array into a single string using a specified delimiter?

In Anqi CMS template design, we often encounter the need to integrate a series of data items into a coherent text.For example, we need to display multiple tags (Tag) in one place, or combine a set of custom parameter values obtained from the database.At this point, the `join` filter comes into play, which can efficiently concatenate the elements of an array into a string with the specified separator.### Understand `join`

2025-11-08

How to get the length of a string, array, or key-value pair in the `length` and `length_is` filters of the Anqi CMS template?

In Anqi CMS template development, it is often necessary to dynamically adjust the display of the page according to the length of the data content.Whether it is to truncate text, judge whether the list is empty, or perform simple content verification, understanding how to obtain the length of strings, arrays, or key-value pairs is the foundation of these functions.AnQi CMS provides the `length` and `length_is` filters, which can help developers flexibly handle these requirements.

2025-11-08

How do the `linebreaks` and `linebreaksbr` filters convert newline characters in multi-line text to HTML's `<p>` or `<br/>` tags?

When managing content in Anqi CMS, we often encounter such situations: when the multi-line text entered in the background editing box is displayed on the front-end page, it becomes a single line, or the newline characters are displayed as text.This is because the browser ignores single newline characters (`\n`) by default when rendering HTML.If you want the content to be displayed with paragraph breaks or line breaks like in the editing box, you need to rely on the powerful template filters provided by AnQiCMS, especially `linebreaks` and `linebreaksbr`

2025-11-08