The `index` filter returns the index position or other identifier when searching for a specific value in an array?

Calendar 👁️ 70

In Anqi CMS template development, mastering various filters can make the display of page content more flexible and efficient. Among them,indexThe filter is a commonly used tool for handling array or string search tasks. However, many users may have a question when first encountering it: when searching for a specific value in an array,indexThe filter returns whether it is the index position of this value or some other identifier?

The answer is clear: Anqi CMS.indexThe filter returns the value when searching for a specific value in an array or stringThe index position of the first occurrence of a numberIf the value being searched for does not exist, it will return-1This behavior is similar to the search functions of many programming languages, which provide a straightforward numerical value to represent the position of the element.

Deep understandingindexFilter

indexThe filter is mainly used to determine whether the target (string or array/slice) contains a specific keyword and to provide its position information.The principle of its operation is to find the first occurrence of the keyword.

  1. Search ObjectIt can be used with strings (to find substrings) and arrays/slices (to find elements).
  2. Return value:
    • If the keyword is found, it returns a non-negative integer representing the keywordFirst occurrenceThe starting index position. The index is from0the calculation starts.
    • If the keyword is not found, return-1.
  3. Special circumstances:
    • When searching in a string, if the string containsChineseA Chinese character is considered to occupy a position in the calculation3 positionsThis usually has to do with the byte length of UTF-8 encoding.This needs to be paid special attention to when used, as it may be different from the intuitive feeling of 'one character occupies one position' that we are accustomed to.

indexHow to use the filter

indexThe syntax of the filter is very concise:

{{ obj|index:关键词 }}

Here:

  • objis the target you want to search for, it can be a string variable, or an array (or slice) variable.
  • 关键词in which you want to searchobjthe specific content you want to find.

Actual application example

We will look at several examples in detail.indexHow does the filter work.

Example 1: Searching in a string.

Suppose we have a string.message = "欢迎使用安企CMS(AnQiCMS)".

{% set message = "欢迎使用安企CMS(AnQiCMS)" %}

<div>查找“CMS”的位置:{{ message|index:"CMS" }}</div>
<div>查找“欢迎”的位置:{{ message|index:"欢迎" }}</div>
<div>查找“世界”的位置:{{ message|index:"世界" }}</div>
<div>查找“安企”的位置(注意中文长度):{{ message|index:"安企" }}</div>

The result will be:

查找“CMS”的位置:18
查找“欢迎”的位置:0
查找“世界”的位置:-1
查找“安企”的位置(注意中文长度):0

Here, 'welcome' takes up the 0-5 byte positions, and 'anqi' also takes up the 0-5 byte positions, so the index of 'anqi' is still 0.The index of the first 'C' is 18 because the six Chinese characters '欢迎使用安企' occupy 18 bytes in length (6 characters * 3 bytes/character).

Example 2: Searching in an array.

Now we create a string array and find elements within it. We can usesplita filter to split a string into an array by delimiter.

{% set features = "安企CMS,AnQiCMS,内容管理系统,免费建站系统,免费模板"|split:"," %}

<div>在数组中查找“内容管理系统”的位置:{{ features|index:"内容管理系统" }}</div>
<div>在数组中查找“高级SEO”的位置:{{ features|index:"高级SEO" }}</div>

{% set searchKeyword = "免费模板" %}
<div>在数组中查找“{{ searchKeyword }}”的位置:{{ features|index:searchKeyword }}</div>

The result will be:

在数组中查找“内容管理系统”的位置:2
在数组中查找“高级SEO”的位置:-1
在数组中查找“免费模板”的位置:4

when searching within an array,indexThe filter performs an exact match and does not consider substrings as string search does.For example, if you search for "management", it cannot be found in an array containing "Content Management System" because it is not an independent element.

Example three: combining conditional judgment using

indexThe filter returns a numerical result, especially suitable forifcombining with logical judgment tags to achieve more complex template logic.

{% set userRole = ["admin", "editor", "viewer"] %}
{% set currentUser = "editor" %}

{% if userRole|index:currentUser != -1 %}
    <p>当前用户 "{{ currentUser }}" 拥有 "{{ currentUser }}" 角色。</p>
{% else %}
    <p>当前用户 "{{ currentUser }}" 没有找到相应的角色。</p>
{% endif %}

{% set guestUser = "guest" %}
{% if userRole|index:guestUser != -1 %}
    <p>当前用户 "{{ guestUser }}" 拥有 "{{ guestUser }}" 角色。</p>
{% else %}
    <p>当前用户 "{{ guestUser }}" 没有找到相应的角色。</p>
{% endif %}

The result will be:

<p>当前用户 "editor" 拥有 "editor" 角色。</p>
<p>当前用户 "guest" 没有找到相应的角色。</p>

By checkingindexWhether the result of the filter is not equal-1We can easily determine whether a value exists in the target and render different content blocks accordingly.

Summary

Of Security CMSindexA filter is a feature that is intuitive and practical, used to find the numeric index position of the first occurrence of a specific value in a string or array, and return it if not found-1. Understanding its working principle, especially the counting rules of Chinese in string search, can help us build template logic more accurately, thus efficiently managing and displaying website content.


Frequently Asked Questions (FAQ)

How to determine if a value exists in an array or string without concerning the specific position?

If you only need to determine whether a value exists without knowing its specific location, you can usecontainfilter.containThe filter directly returns a boolean value (TrueorFalseDoes it include this value, which is more concise and clear when only an existence check is needed.

2.indexCan the filter find subarrays or patterns (regular expressions) within a string?

indexThe filter performs direct value or substring matching and does not support searching within subarrays.For strings, it only searches for exact substrings and does not support regular expression pattern matching.If a more complex pattern matching is required, it may be necessary to consider processing in the business logic layer and passing the processed data to the template.

3. What if I need to get the index positions of all matches?indexCan the filter do that?

indexThe filter only returns keywordsFirst occurrencethe index position. It cannot directly obtain the index positions of all matching items.To implement this feature, you may need to perform more complex logic processing in Go language code outside the template, or preprocess the data into a structure containing all indices before passing it to the template.On the template level, it focuses on the efficiency and conciseness of the first search.

Related articles

How to get the position of the first occurrence of a keyword in the AnQiCMS article title?

In website content operations, we sometimes need to refine the processing of article titles, such as highlighting a keyword or organizing content based on the position of the keyword.In terms of AnQiCMS, the system provides a powerful template engine, combined with its built-in filters, we can easily achieve these requirements.Today, let's discuss how to accurately obtain the position of the first occurrence of a keyword in the article title of AnQiCMS.### Core Function Unveiling: `index` Filter It can be used in AnQiCMS

2025-11-07

How does the `count` filter handle the counting logic for Chinese character strings?

In daily content operations, we often encounter scenarios where we need to perform statistical analysis on content, such as counting the number of times specific keywords appear, checking the frequency of repetition of certain elements in the content, etc.AnQiCMS provides many practical template filters to help us achieve these functions, where the `count` filter is a powerful tool for counting.When dealing with content containing Chinese characters, it is particularly important to understand how the `count` filter performs counting.

2025-11-07

How to use the `count` filter to analyze the keyword density on AnQiCMS templates?

In website operation and Search Engine Optimization (SEO), keyword density is a common but easily misunderstood concept.It refers to the ratio of the number of times a keyword appears in the web content to the total number of words, usually expressed as a percentage.Although the algorithms of search engines are more complex now, it is no longer the era when simply stacking keywords could achieve good rankings, but moderately paying attention to keyword density can help us ensure that the content theme is clear and convey the core information of the page to the search engine.

2025-11-07

The `count` filter is it for exact match or partial match when calculating the number of occurrences of a value in an array?

In Anqi CMS template development, the `count` filter is a very practical tool that can help us easily count the number of times a specific value appears.However, when using this filter, many users may wonder: when it calculates the number of times a value appears, is it performing an exact match, or a more flexible partial match?The answer is not one-size-fits-all, but varies depending on the data type.

2025-11-07

What result does the `index` filter return when the keyword does not exist in the string?

In the flexible and powerful template system of AnQiCMS, we often need to process and judge various text content on the page.Among them, the `index` filter is a very practical tool that helps us quickly locate the first occurrence of a keyword in a string or array. Then, when we need to search for a keyword that does not exist at all in the target string or array, what result will the `index` filter return to represent this situation?The answer is: it will return a clear **-1**.In the conventions of programming and template processing

2025-11-07

The `index` filter calculates the position of Chinese characters in a string, how many positions does a Chinese character occupy?

In AnQi CMS template development, the `index` filter is a very practical tool that helps us locate the position of a specific substring in a string.However, when dealing with content containing Chinese characters, its performance in position calculation may confuse some users.How many positions does a Chinese character occupy in the `index` filter?What kind of logic is hidden behind this? Let's delve deeper together.### `index` filter's working principle In simple terms

2025-11-07

How to dynamically get the actual character length of the article abstract in AnQiCMS template?

In website content operation, we often need to fine-tune the display form of content, especially for information such as article summaries, which not only affects the first impression of users but also plays an important role in the inclusion of search engines.In AnQiCMS (AnQiCMS) flexible and powerful template system, getting the actual character length of the article abstract is a very practical skill, which can help us achieve more accurate content presentation.Why do you need to get the actual character length of the article summary?The article abstract is the core essence of the content, usually used on list pages

2025-11-07

The `length` filter considers empty values or nil elements when calculating the length of an array or a key-value pair?

AnQiCMS template `length` filter: Deep understanding of its length calculation mechanism During the development of AnQiCMS templates, we often need to judge the length of strings, lists (arrays), or key-value pairs (Maps) to control the display logic of content.The `length` filter is designed for this purpose, it helps us get the length information of these data types.However, many users are confused about whether it considers null or `nil` elements when calculating length. Next

2025-11-07