How to determine if a string or array contains a keyword using the `contain` filter in the AnQi CMS template?

Calendar 👁️ 66

In Anqi CMS template development, we often need to dynamically adjust the display of the page based on the different characteristics of the data.Among them, the need to judge whether a string or array contains a certain keyword or element is a very basic but extremely common requirement. At this time,containThe filter has become a powerful tool in our hands, it can help us easily achieve this goal.

containThe filter is mainly used to check if a variable (whether it is a string, array, or key-value pair and structure) contains a specific content. Its result will be a boolean value: if it contains, it will returnTrue; if it does not contain, it will returnFalseThis enables us to write smarter, more flexible conditional logic in the template.

Let's understand through specific examples.containThe application of filters in different scenarios.

Determine if the string contains a keyword

When your variable is a piece of text,containThe filter can quickly check if this text contains a substring.This is very useful in many scenarios, such as determining whether the title or abstract of an article mentions a specific word.

Example:

{% set articleTitle = "安企CMS:企业建站好帮手,效率提升秘籍" %}

{% if articleTitle|contain:"CMS" %}
    <p>该文章标题中包含了 "CMS",是关于内容管理系统的重要文章。</p>
{% else %}
    <p>该文章标题中不包含 "CMS"。</p>
{% endif %}

In the above example,articleTitleThe variable indeed contains “CMS”, so the condition is met, and the first paragraph of the page will be displayed.

Check if an element exists in an array (slice)

If your variable is an array (often represented as a slice in Go templates),containThe filter can determine if there is a completely matching element in this array.This is used to check if a specific tag is included in the list of tags of an article, or if the value of a multi-select field contains a certain option.

Example:

Assumeitem.TagsIs an array containing multiple tags, for example["网站运营", "SEO优化", "内容营销"].

{% set itemTags = ["网站运营", "SEO优化", "内容营销"] %}

{% if itemTags|contain:"SEO优化" %}
    <p>此文章属于 "SEO优化" 类别,内容对搜索引擎优化有帮助。</p>
{% else %}
    <p>此文章不属于 "SEO优化" 类别。</p>
{% endif %}

Here, becauseitemTagsThe array contains the element 'SEO optimization', so the condition is met, and the first paragraph of text will be displayed on the page.

Determine whether a key exists in a key-value pair (map) or a structure (struct)

When your variable is an associative array (such as system settings parameters, custom fields) or a structure,containThe filter can be used to determine if a specific key name (field name) exists.This is very useful for checking if custom fields exist, to avoid errors during template rendering due to missing fields, or to dynamically display content based on the availability of different fields.

Example:

Assumeproductis a structure or associative array that may contain custom fields.

{% set product = {name:"智能手机", price:2999, color:"黑色"} %}

{% if product|contain:"color" %}
    <p>此产品有颜色选项:{{ product.color }}</p>
{% else %}
    <p>此产品没有颜色选项。</p>
{% endif %}

In this example,productContains the 'color' key, so the page will display a paragraph with color information.

Combinesetandiftags to implement more complex logic

containFilters are usually used with{% set %}Use the tag in conjunction, which assigns the judgment result to a temporary variable and then passes it through{% if %}Use the tag for conditional judgment, thus realizing more complex and clear template logic.

{% set pageContent = "欢迎来到安企CMS的官方网站,这里提供高效、易用的内容管理解决方案。" %}
{% set isOfficialSite = pageContent|contain:"官方网站" %}

{% if isOfficialSite %}
    <div class="official-badge">
        <img src="/static/images/official.png" alt="官方认证">
        <p>此页面为官方内容,请放心浏览。</p>
    </div>
{% else %}
    <p>此页面可能为用户分享内容,信息仅供参考。</p>
{% endif %}

This style not only makes the logic more readable, but also convenient for reuse in subsequent templatesisOfficialSiteThis judgment result

Summary of practical application scenarios

  • Content dynamic highlighting:If the article content contains specific keywords, you can highlight the keywords.
  • Personalized recommendation: Based on the user's browsing history tags, judge whether the recommended content contains tags that the user is interested in.
  • Navigation menu activation state:Determine if the current URL contains a menu link, and automatically add to the menu itemactiveClass.
  • Field existence check:Before displaying custom field content, usecontainCheck if the field exists to avoid displaying unnecessary content due to an empty field.

Some important points to note.

  • Case sensitive: containThe filter is case-sensitive when matching. For example,"Apple"|contain:"apple"It will returnFalseIf a case-insensitive match is required, it may be necessary to convert the string to uppercase or lowercase before the judgment.
  • Array elements match exactly:For array types,containThe elements must be an exact match, no fuzzy matching will be performed.
  • Key name/field name matching:For key-value pairs or structures, it checks the key name or field name, not the value.

containThe filter is a powerful and flexible tool in the Anqi CMS template.Mastery of its usage can help us write more dynamic, adaptable, and concise templates, thereby significantly improving the management efficiency and user experience of website content.


Frequently Asked Questions (FAQ)

  1. containIs the filter case sensitive?Yes,containThe filter is case-sensitive when matching. For example,{{"AnQiCMS"|contain:"anqicms"}}It will returnFalseIf you need a case-insensitive match, consider performingcontaina comparison after converting the string to a uniform case (for example, all to lowercase) before comparing.

  2. exceptcontainWhat similar filter functions can be used to check the content of Anqi CMS template?Anqi CMS template also providescountFilters andindexfilter.countUsed to calculate the number of times a keyword or element appears in a string or array, andindexReturns the first occurrence position of a keyword or element (if not found, returns -1). Both return numbers, different fromcontainReturning a boolean value, you can choose to use it according to your specific needs.

  3. containCan the filter be used to check if the 'value' of a custom field contains a certain keyword? containThe filter cannot be used directly to check if the value of a custom field contains a specific keyword unless thevalue itself is a string. It is mainly used for:

    1. Check if the string itself contains a substring.
    2. Check if an element exists in the array.
    3. Check if a key-value pair or structure contains a certain "key name" or "field name". If you want to check if the value of a custom field contains a specific keyword, you need to first get the value of that custom field and then use that value ascontainThe input of the filter. For example,{{ archive.CustomFieldValue | contain:"关键词" }}.

Related articles

How do the `center`, `ljust`, and `rjust` filters align strings to the center, left, or right at a specified length?

In the presentation of website content, the format and alignment of text often directly affect the reader's reading experience.Especially when creating AnQiCMS templates, we often encounter the need to center, left-align, or right-align titles, phrases, or data lists according to a specific length.Although most layouts rely on CSS styles, in some cases, using built-in string filters in templates can be more flexible and efficient to achieve these delicate text layouts.

2025-11-08

How to use `capfirst`, `lower`, `upper`, `title` filters to perform different case conversions on English strings?

When using AnQiCMS to build and manage website content, we often need to refine the text control, especially in the presentation style of the content.English string case conversion is a common requirement, whether it is to unify style, optimize title display, or meet specific layout requirements, AnQiCMS's powerful template filter can provide a flexible solution.

2025-11-08

In AnQi CMS template, how does the `add` filter implement the functionality of adding numbers or concatenating strings?

In AnQi CMS template development, we often need to perform some basic data processing, such as simple addition operations on numbers, or combining different text fragments to form new strings.To meet these common and practical needs, AnQi CMS provides a very convenient template filter——`add`.This is a compact yet powerful tool that can help us easily perform addition and string concatenation, making template logic more flexible.

2025-11-08

The `pluralize` filter affects its output when handling different quantities, such as 0, 1, or multiple items?

When building a website, the way content is presented often determines the subtlety of user experience.A small detail, such as correctly displaying the singular and plural forms of words according to the number, can make the website content appear more professional and natural.AnQiCMS provides a very practical tool to handle such cases, that is the `pluralize` filter.### Flexible Handling of Quantity Changes: AnQiCMS `pluralize` Filter Usage Details In the dynamic content display of the website, such as displaying product inventory

2025-11-08

How to use the `count` filter to calculate the number of times a keyword appears in a string or array?

In website content operation, we often need to understand the frequency of certain specific keywords appearing in articles, product descriptions, and other text.This is very valuable for SEO optimization, content quality analysis, and even just data statistics.AnQi CMS provides a powerful and flexible template system, which includes a very practical `count` filter, which can help us easily achieve this goal.### Understanding the `count` filter In simple terms, `count`

2025-11-08

How to remove specified characters from any position in the string using the `cut` filter in the Anqi CMS template?

In website content operation, we often need to process strings, such as cleaning up extra characters, or standardizing the display content.AnQiCMS template engine provides a series of powerful filters to help us complete these tasks, among which the `cut` filter is a very practical tool, specifically used to remove specific characters from any position in a string.### Understanding the working principle of the `cut` filter The `cut` filter plays a very direct role in the AnQi CMS template

2025-11-08

How do the `date` and `time` filters display `time.Time` type time values in a specified format?

In AnQi CMS template design, flexibly displaying dates and times is a key aspect of content presentation.In order to meet this refined requirement, AnQi CMS provides a series of practical time processing tools, among which the `date` and `time` filters are important functions for formatting and displaying `time.Time` type time values.

2025-11-08

How to set default values for `default` and `default_if_none` filters to avoid displaying blank when the variable is empty or `nil`?

In daily website content management, we often encounter such situations: certain variables may be empty due to unfilled content, missing data, or other reasons (or in programming terms, `nil`).If not handled, these variables may be displayed as blank areas on the front-end page, which not only affects the beauty of the page but may also confuse visitors and reduce the professionalism of the website.AnQiCMS (AnQiCMS) is well aware of this pain point

2025-11-08