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

Calendar 👁️ 74

In the template development of Anqi CMS and daily content operations, we often encounter the need to dynamically display information based on specific attributes or keywords of the content.In order to achieve personalized content recommendations, emphasize the specific themes of articles, or control the display of page elements based on certain indicators in the data, accurately determining whether a string or array contains a specific keyword is a very practical skill.

The Anqi CMS template system uses a syntax similar to the Django template engine, built-in with rich filters and tags, which can help us easily achieve such judgments.Next, we will delve into how to determine whether a string or array in the Anqi CMS template contains specific keywords, and provide some practical methods and scenario examples.


UsecontainFilter for keyword judgment

In the AnQi CMS template, the most direct and commonly used method is to use the built-incontainA filter. This filter is used to detect whether a string or an array (slice) contains a specified keyword. Its return value is a boolean type (TrueorFalse), very suitable for conditional judgment tags{% if %}Combine usage.

Basic usage:

{{ obj|contain:关键词 }}

Among them,objCan be a string variable or an array variable关键词which is the specific string you want to find.

Example 1: Determine if a string contains a keyword

Suppose we pass througharchiveDetailTag to get the title of an articlearchive.Title, and hope to determine if it contains the word 'tutorial':

{% set articleTitle = archive.Title %} {# 假设 archive.Title 的值为 "安企CMS模板制作教程" #}

{% if articleTitle|contain:"教程" %}
    <p>这篇文章标题中包含了“教程”字样,这可能是一个入门指导!</p>
{% else %}
    <p>这篇文章标题中未包含“教程”字样。</p>
{% endif %}

In the above example, ifarticleTitlethe content is "Anqi CMS template creation tutorial", then the conditionarticleTitle|contain:"教程"It will returnTrueand display the corresponding prompt message.

Example two: Determine if an array contains a specific element

Sometimes, data exists in the form of an array, such as a list of Tag tags in an article. We can usetagListLabel to get the Tag list and then judge whether a specific Tag exists:

{% tagList tags with itemId=archive.Id %} {# 假设 tags 数组包含 ["网站优化", "SEO", "内容营销"] #}

{% if tags|contain:"SEO" %}
    <span class="highlight-tag">本文专注于SEO优化</span>
{% else %}
    <span>本文未涉及SEO优化</span>
{% endif %}

{% endtagList %}

In this scenario,tagsThe variable is an array containing multiple strings.tags|contain:"SEO"It will check if there is an element with the value 'SEO' in the array.

Example three: Determine if there is a specific key name in the key-value pair (Map/Struct).

containThe filter can also be used to determine if a specific key (key) exists in the key-value pair (or structure).This is very useful when handling custom fields in the background or some configuration data.

{% set extraParams = archive.Extra %} {# 假设 extraParams 是一个包含自定义字段的Map,如 { "author": "张三", "source": "官网" } #}

{% if extraParams|contain:"author" %}
    <p>作者:{{ extraParams.author }}</p>
{% else %}
    <p>未指定作者信息。</p>
{% endif %}

Here, extraParams|contain:"author"Will checkextraParamsDoes it exist namedauthorkey?


Other methods of judgment keywords:indexandcountFilter

exceptcontainOutside the filter,indexandcountThe filter can also indirectly help us judge whether a string or array contains a specific keyword and provide more detailed information.

1.indexFilter: Get the position of a keyword

indexThe filter will return the first occurrence position (index) of a keyword in a string or array, if not found then it will return-1We can use this feature to determine if a keyword exists.

Basic usage:

{{ obj|index:关键词 }}

Example: Combineindexthe judgment.

{% set articleContent = archive.Content %} {# 假设内容中包含 "安企CMS是一款高效的CMS系统" #}

{% if articleContent|index:"高效" > -1 %}
    <p>内容中提到了“高效”,首次出现在第 {{ articleContent|index:"高效" }} 个字符处。</p>
{% else %}
    <p>内容中未提及“高效”。</p>
{% endif %}

IfindexThe returned value is greater than-1This means that the keyword exists. This method is suitable for scenarios where you are not only concerned about the existence of the keyword, but also about the position of its first occurrence.

2.countFilter: Calculate the number of times a keyword appears

countThe filter can count the number of times a keyword appears in a string or array. If the count is greater than0, it indicates that the keyword exists.

Basic usage:

{{ obj|count:关键词 }}

Example: Combinecountthe judgment.

{% set articleContent = archive.Content %} {# 假设内容中包含 "安企CMS是一款高效的CMS系统,安企CMS致力于提供高效解决方案。" #}
{% set cmsCount = articleContent|count:"CMS" %}

{% if cmsCount > 0 %}
    <p>内容中提到了“CMS”共 {{ cmsCount }} 次。</p>
{% else %}
    <p>内容中未提及“CMS”。</p>
{% endif %}

WhencountThe number returned by the filter is greater than0This indicates that the keyword exists. This method is very useful when it is necessary to understand the frequency of keyword occurrence.


The application scenario: making content more intelligent and expressive

These keyword judgment functions are widely used in the operation of actual websites and template design:

  • Display recommended icon or corner mark dynamically:For example, if the product title contains "new" or "special offer", an "new launch" or "time-limited offer" corner mark can be automatically added to the product image.
  • Personalized content guidance:Based on the content of the article the user is browsing (for example, if the article title or keywords contain "Go language"), recommend more tutorials or related products about Go language in the sidebar.
  • Template style control:If the body of the article contains certain specific phrases (such as "Click here to download"), these phrases can be applied special CSS styles to make them more prominent.
  • List content filtering and grouping:In the background custom list, by judging whether a custom field contains a specific value, to conditionally filter or group the list items displayed on the front end.
  • Targeted advertising or marketing information:Dynamically insert relevant advertising or promotional information based on page theme or content keywords to improve conversion rates.

Details to pay attention to.

When using these filters, there are several details that are worth noting:

  • Case Sensitive:By default,contain/indexandcountFilters are allCase sensitiveThis means that "CMS" and "cms" are treated as different keywords.If you need to perform a case-insensitive judgment, you need to convert both the source string and the keyword to the same case (such as lowercase) before making the judgment, for example{% if articleTitle|lower|contain:"cms" %}.
  • Data source:Ensure that the data you provide to the filter (string or array) is correct. Typically, these data come from various tags of Anqie CMS, such asarchiveDetailreturnedarchive.Title/archive.ContentOrarchiveListin the loopitem.Keywordsetc.
  • Performance consideration: For most websites and content volume, use these in the template

Related articles

How to achieve text centering or left-right alignment formatting in templates for AnQiCMS?

In web design, the layout and alignment of content are key elements of user experience.No matter if you want to center the title or align the paragraph text to the left, AnQiCMS provides a flexible template mechanism, combined with standard Web technology, which can easily meet these needs.AnQiCMS as a content management system developed based on the Go language has its core advantages in providing efficient, customizable content management and data output.It uses a syntax similar to the Django template engine, allowing you to combine system data (such as article titles, content, etc.) with

2025-11-08

How to automatically capitalize the first letter of an article title, or to achieve full uppercase/lowercase conversion?

In content operation, a standardized and unified title format is crucial for the brand image of the website and the user reading experience.To enhance visual tidiness or to meet specific design styles, automatically adjusting the case of the article title is a very practical feature.AnQiCMS as a flexible content management system, provides a convenient way to help us achieve this goal without complex programming, and it can be easily handled.

2025-11-08

How to correctly escape special characters in the AnQiCMS template to avoid display errors?

In website content management, we often need to display text containing various special characters.If these special characters are not handled correctly, it may lead to page layout chaos, functional anomalies, and even security vulnerabilities.AnQiCMS provides a powerful mechanism to help us handle these special characters during template rendering, ensuring the correct display of content and the security of the website.

2025-11-08

How to safely concatenate string and numeric variables in the AnQiCMS template?

During the development of AnQiCMS templates, we often need to combine different text segments, numerical information, and even system variables to form a complete output content, such as building dynamic links, displaying formatted data, or generating user-friendly prompt information.This process involves concatenating strings and numeric variables, and how to safely and efficiently complete this operation is an indispensable aspect of template development.AnQiCMS's powerful template engine provides a variety of flexible mechanisms to support these needs.AnQiCMS template engine syntax is similar to Django

2025-11-08

How to count the number of times a certain keyword appears in the article content in the AnQiCMS template?

In content operation, understanding the frequency of keywords in articles is an important part of SEO optimization and content strategy analysis.By counting the frequency of keywords, we can better evaluate the density, relevance, and even discover potential optimization spaces.AnQiCMS provides a powerful and flexible template system,配合 its built-in content filter, we can easily count the number of occurrences of specific keywords in the article content.### Understanding the need: Why do we need to count keywords?Count the number of times a keyword appears in an article, mainly including the following practical application scenarios: 1.

2025-11-08

How to remove specific characters or extra spaces from AnQiCMS template variables?

In website content operations, we often encounter such situations: the template variable content retrieved from the database may contain some unnecessary characters, extra spaces, or formats that are not satisfactory.These subtle details, if not handled properly, may affect the aesthetics of the page, user experience, and even cause interference with search engine optimization (SEO).AnQiCMS provides powerful template filtering functionality, helping us easily clean and format these variables.The template syntax of AnQiCMS is similar to Django engine

2025-11-08

How to format Unix timestamp into a readable date and time format in AnQiCMS template?

In website content management, time information plays a crucial role, whether it is the publication date of articles, update time, or the submission time of comments, the record of time is indispensable.Databases usually store these time data in a concise and efficient format - Unix timestamps.However, for the end user, a string of numbers in a timestamp is not as intuitive and easy to understand as “October 27, 2023 14:30”.

2025-11-08

What are the differences and applicable scenarios between the `default` and `default_if_none` filters when the template variable is empty?

In AnQi CMS template design, reasonably handling variables that may be empty is the key to ensuring the integrity and smooth user experience of website content display.When a template variable has no value or is in an 'empty' state, we usually do not want blank or error messages to appear on the page, but rather we would like to display a preset default content.At this time, the `default` and `default_if_none` filters provided by Anqicms come into play.They can all provide default values for variables

2025-11-08