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

Calendar 👁️ 68

In website content operation, 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 meet 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.

The core feature revelation:indexFilter

To find the position of a specific keyword within a string in the AnQiCMS template, we need to use a very useful built-in featureindexA filter. This filter is used to find the first occurrence of a substring in a main string.

Its basic usage is very intuitive:

{{ 主字符串 | index: "要查找的关键词" }}

When you pipe a string through|pass toindexA filter that, when provided with a keyword as a parameter, returns the starting position of the first occurrence of that keyword in the main string. This position is from0Counting starts, that is, if the keyword is at the beginning of the string, it will return0. If the keyword is not found in the string,indexThe filter will return-1.

There is a particular point that needs to be paid attention to, especially when dealing with titles containing Chinese characters:indexThe filter will treat a Chinese character as occupying 3 bytes of space when calculating positions.This means that if your title contains Chinese and you try to search for an English keyword, the returned position may be larger than what you intuitively think in terms of character positions.For example, in a string"你好世界AnQiCMS"search for in"AnQiCMS",indexThe position returned will be12Because the four Chinese characters in “Hello World” occupy4 * 3 = 12A position).

Practical exercise: Find keywords in the article title

Now, let's takeindexThe filter is applied to the article titles of AnQiCMS.Generally, we would retrieve the title of the current article on the article detail page, or get the title of each article while iterating through the article list.

First, assume we are on an article detail page, and we need to get the current article title and search for keywords in it:

{# 假设这是在文章详情页,archive 是当前文章对象 #}
{% set articleTitle = archive.Title %}
{% set searchKeyword = "AnQiCMS" %} {# 我们要查找的关键词 #}

{% set keywordPosition = articleTitle|index:searchKeyword %}

{% if keywordPosition != -1 %}
    <p>关键词 "{{ searchKeyword }}" 在标题 "{{ articleTitle }}" 中的首次出现位置是:{{ keywordPosition }} (从0开始计数)</p>
    {# 我们可以进一步利用这个位置信息 #}
    {% set keywordLength = searchKeyword|length %} {# 获取关键词的字节长度,用于后续截取 #}
    {% set textBefore = articleTitle|slice:":keywordPosition" %} {# 截取关键词前面的部分 #}
    {% set textAfter = articleTitle|slice:"(keywordPosition + keywordLength):" %} {# 截取关键词后面的部分 #}

    <p>标题中关键词前面的内容:<span>{{ textBefore }}</span></p>
    <p>标题中关键词后面的内容:<span>{{ textAfter }}</span></p>

    {# 甚至可以在模板中将关键词高亮显示,但这需要更复杂的字符串操作或在后端处理 #}
    {# 简单示例:替换关键词 #}
    {% set highlightedTitle = articleTitle|replace:"(searchKeyword, <mark>" ~ searchKeyword ~ "</mark>)" %}
    <p>高亮后的标题(简单替换):{{ highlightedTitle|safe }}</p>

{% else %}
    <p>在标题 "{{ articleTitle }}" 中未找到关键词 "{{ searchKeyword }}"。</p>
{% endif %}

This code first goes through{% set ... %}The tag defines the article title and the keywords we want to find. Then, it usesindexthe filter to get the position of the keywords. If the position is not-1This indicates that the keyword exists and its position will be displayed.

You cansearchKeywordSet it as a variable so that it can be dynamically retrieved from URL parameters or other configurations, making the search more flexible.

Further: combine other filters to implement advanced operations

indexThe filter is powerful, but combined with other AnQiCMS template filters, it can achieve richer title processing functions.

  1. Check if the keyword exists:containFilterIf you only need to know if the title contains a specific keyword without knowing the exact location,containthe filter will be more concise. It returns directlytrueorfalse.

    {% if articleTitle|contain:"重要" %}
        <p>标题中包含“重要”这个词。</p>
    {% endif %}
    
  2. to perform a case-insensitive search:lowerorupperFilter indexThe filter is case-sensitive. If you want to perform a case-insensitive search, you can convert the title and keywords to lowercase (or uppercase) before comparing.

    {% set lowerTitle = articleTitle|lower %}
    {% set lowerKeyword = searchKeyword|lower %}
    {% set caseInsensitivePosition = lowerTitle|index:lowerKeyword %}
    
    {% if caseInsensitivePosition != -1 %}
        <p>不区分大小写查找,关键词 "{{ searchKeyword }}" 在标题中存在。</p>
    {% endif %}
    
  3. Extract content before and after the keyword:sliceFilterAs shown in the previous example, once we have obtained the starting position of the keyword (keywordPosition) and the length of the keyword (searchKeyword|length), we can usesliceA filter to extract content around keywords in titles, which is very useful for displaying summaries or highlighting context.

    {# 结合上面的例子 #}
    {% set textBefore = articleTitle|slice:":keywordPosition" %}
    {% set textAfter = articleTitle|slice:"(keywordPosition + keywordLength):" %}
    

By combining these flexible filter options, you can perform various customized keyword analysis and display on article titles in the AnQiCMS template.

Summary

AnQiCMS provides a template engine that offersindexA filter that allows us to accurately find the first occurrence of a specific keyword in the article title. Although attention must be paid to the byte counting characteristics of Chinese characters when processing, but by using it flexiblyindexCombineset/contain/lower/sliceWith other filters, we can achieve the search, judgment, extraction, and even simple content recombination of title keywords, thereby bringing more possibilities for the dynamic display of website content and user experience.

Related articles

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

How to count the total number of times a specific keyword appears in the content of AnQiCMS articles?

In content operation, the reasonable layout and statistics of keywords are an indispensable part of optimizing search engine performance and improving user experience.A precise keyword distribution can not only help search engines better understand your content, but also allow users to find the information they need faster.AnQiCMS (AnQiCMS) relies on its powerful template engine to provide us with a flexible way to count the occurrences of specific keywords in article content, thereby assisting our content strategy.

2025-11-07

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

In Anqi CMS template development, proficiently using various filters can make the display of page content more flexible and efficient.Among them, the `index` filter is a commonly used tool for handling array or string search tasks.However, many users may have a question when they first contact: When searching for a specific value in an array, does the `index` filter return the index position of the value or some other identifier?

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