How to determine if a string, array, or map contains a specific keyword and display the boolean result?

Calendar 81

In Anqi CMS template development, we often need to dynamically adjust the display of the page based on the specific attributes or keywords of the content.For example, determine whether an article's title contains a certain word, whether a product category is on a certain list, or whether a configuration item exists.The Anqi CMS powerful template engine provides various filters and operators that can help us easily implement these judgments and obtain clear Boolean (True/False) results.

Let's delve deeper into how to implement these flexible judgments in AnQi CMS.

Core function:containFilter

When you need to determine whether a string of text, an array element (or a Go language slice), or a key name in a map/struct contains a specific keyword,containThe filter is your preferred tool. It returns a boolean value, directly telling you the result.True(including) orFalse(excluding).

Basic usage

containThe usage of the filter is very intuitive:

{{ obj|contain:"关键词" }}

Among themobjIt is the variable you need to check, while"关键词"It is the specific content you want to find.

In the application of conditional judgment

Generally, we willcontainThe result of the filter is usedifIn the logic judgment tag, thus controlling the display logic of the template.

{% if "欢迎使用安企CMS(AnQiCMS)"|contain:"CMS" %}
    <p>这段文字中包含了"CMS"!</p>
{% else %}
    <p>这段文字中没有找到"CMS"。</p>
{% endif %}

You can also firstcontainThe result of the filter is stored in a variable, which helps to enhance the readability and reusability of the code:

{% set sourceText = "安企CMS,高效内容管理" %}
{% set isFound = sourceText|contain:"内容管理" %}

{% if isFound %}
    <p>内容中提到了“内容管理”这个关键词。</p>
{% else %}
    <p>内容中未提及“内容管理”。</p>
{% endif %}

Judgment for different data types

containThe filter shows its flexibility when handling different data types:

  1. Keyword search in a string:WhenobjWhen it is a string,containIt will check if the string contains the specified keyword as a substring.

    {% set articleTitle = "安企CMS:打造企业级内容管理平台" %}
    {% if articleTitle|contain:"企业级" %}
        <p>文章标题强调了“企业级”特性。</p>
    {% else %}
        <p>文章标题未突出“企业级”特性。</p>
    {% endif %}
    
  2. Find element in an array (slice):Whenobjwhen it is an array,containCheck if there is an element in the array that matches the specified keyword exactly.

    {% set tags = ["CMS", "GoLang", "企业", "效率"] %}
    {% if tags|contain:"GoLang" %}
        <p>这篇文章的标签包含了“GoLang”</p>
    {% else %}
        <p>这篇文章的标签不包含“GoLang”</p>
    {% endif %}
    
  3. The key name lookup of (map) or (struct):Whenobjwhen it is a (map) or (struct),containIt will judge whether there is a specified key name (or field name) present. It is important to note that it judgeskey namenot the key-value pair.

    {# 假设有一个名为 `contactInfo` 的映射变量 #}
    {% set contactInfo = {"email": "[email protected]", "phone": "123456789"} %}
    {% if contactInfo|contain:"phone" %}
        <p>联系方式中提供了电话号码。</p>
    {% else %}
        <p>联系方式中未提供电话号码。</p>
    {% endif %}
    

It has a related but slightly different purpose:inoperator

exceptcontainFilter, the Anqi CMS template engine also supportsinOperator, it is used in some scenarios withcontainSimilar, but focuses onExact matchthe existence of elements.inThe operator is mainly used to determine whether an element exactly exists in an array (slice) or a mapkey.

{# 判断数字 5 是否存在于数字列表 simple.intmap 中 #}
{% if 5 in simple.intmap %}
    <p>数字 5 存在于列表中。</p>
{% else %}
    <p>数字 5 不存在于列表中。</p>
{% endif %}

{# 判断字符串 "Hello" 是否存在于字符串列表 simple.misc_list 中 #}
{% if "Hello" in simple.misc_list %}
    <p>“Hello”存在于列表中。</p>
{% else %}
    <p>“Hello”不存在于列表中。</p>
{% endif %}

containwithinSummary of the differences:

  • containFilter:
    • When used for strings, it performssubstring search.
    • Performing when used with an arrayExact element matching.
    • Check when used with a map/structureCheck if the key (field name) exists.
  • inoperator:
    • Performing when used with an arrayExact element matching.
    • Check when used with a mapDoes the exact key name exist.
    • Cannot be used directly for substring search in strings.

In simple terms, if you need to perform substring fuzzy matching on strings, or determine if the key name exists in the mapping,containIs a more general choice. If you just need to check if an element exists in an array, or if a key exists in a map,inthe operator is more concise.

Other auxiliary judgment methods

In addition to the methods mentioned above that directly return boolean results, there are some filters that indirectly express the states of 'include' or 'exclude' by returning specific numbers:

  • indexFilter:Used to find the first occurrence position of a keyword in a string or array. If returned-1means not found.
    
    {% if "安企CMS"|index:"CMS" != -1 %}
        <p>“CMS”在字符串中出现。</p>
    {% endif %}
    
  • countFilter:Used to calculate the number of times a keyword appears in a string or array. If returned0means not found.
    
    {% if "安企CMS"|count:"CMS" > 0 %}
        <p>“CMS”在字符串中至少出现一次。</p>
    {% endif %}
    
    These auxiliary methods can also perform boolean judgments through simple comparison operations while obtaining more information (such as position, frequency).

By flexible applicationcontainFilters andinCombined with operators,ifLogical tag, you can easily implement various complex conditional judgments in the Anqi CMS template, making your website content display more dynamic and intelligent.


Frequently Asked Questions (FAQ)

  1. containIs the filter case sensitive?Yes,containThe filter performs case-sensitive string matching. For example,"AnQiCMS"|contain:"cms"It will returnFalse. If you need to perform a case-insensitive judgment, you can consider usinglowerorupperThe filter converts the string to be checked and the keyword to the same case (e.g., all to lowercase) before usingcontainFilter. Example:{% if articleTitle|lower|contain:keyword|lower %}

  2. How to determine if a string contains multiple keywords (such as both 'CMS' and 'GoLang')?You canifUsing in a sentenceandororLogical operators to determine if multiple keywords are included.

    • Include both (and): {% if articleTitle|contain:"CMS" and articleTitle|contain:"GoLang" %}
    • Include any of the following (or): {% if articleTitle|contain:"CMS" or articleTitle|contain:"GoLang" %}
  3. containCan the filter determine if the key-value in the map contains a specific keyword?No.containWhen used with a map, the filter will only check if the map contains a specifickey name,

Related articles

How to display user registration or group details (such as username, level, avatar) on the front page?

In website operation, displaying rich user-related information on the front page is an effective way to enhance user experience and community activity.Whether it is displaying the author's avatar, the user's level, or the username at registration, these personalized details can make the website more vibrant.AnQiCMS as a powerful content management system provides us with very flexible template tags and data call capabilities, making the display of this information easy and simple.### Understand AnQiCMS user and group data In the AnQiCMS backend

2025-11-08

How to automatically convert URLs and email addresses in text to clickable links and display them?

In website content management, we often encounter scenarios where we need to display various links and email addresses in articles or pages.Manually converting this text to clickable HTML links is time-consuming and prone to errors, especially when the amount of content is large, and the workload is惊人的。AnQi CMS fully understands this pain point of users, built-in efficient and intelligent text processing mechanism, can automatically identify and convert URLs and email addresses, greatly improve the efficiency of content publishing and user browsing experience

2025-11-08

How to format a floating-point number to a specified precision (number of decimal places) for display?

In AnQiCMS, the flexibility of content display is one of its core advantages.When dealing with floating-point numbers that require precise display of decimal places, understanding how to utilize its powerful template engine function is particularly important.Ensure that numbers are presented in the expected format for displaying product prices, statistical data, or technical parameters, which can greatly enhance user experience and the professionalism of the website.The Anqi CMS template syntax borrows from the Django template engine, providing rich filters (Filters) to process and format data.Formatting for floating-point numbers

2025-11-08

How to debug the structure, type, and value of display variables in a template to help troubleshoot display issues?

During the template development process of Anqi CMS, we sometimes encounter situations where variables do not display as expected or the displayed content is incorrect.This may affect the normal functioning of the website, and may also cause deviations in content display, reducing the user experience.We need an efficient and intuitive tool to help us quickly locate the problem.The Anqi CMS provides a very practical built-in filter——`dump`, which can help us clearly view the structure, type, and current value of any variable in the template.

2025-11-08

How to calculate the number of times a certain keyword appears in a string or array and display it?

In the daily work of content operation, we often need to conduct in-depth analysis of website content, one of the common requirements is to understand the frequency of a keyword appearing in a specific string or content block.This is crucial for SEO optimization and also helps us evaluate the relevance and quality of the content.AnQi CMS as an efficient enterprise-level content management system provides us with very convenient built-in tools to solve this problem, that is the powerful `count` filter.

2025-11-08

How to remove spaces or specified characters from the beginning, end, or all positions of a string and then display it?

In website content operation, we often encounter situations where strings contain unnecessary spaces or specific characters.These seemingly minor issues may affect the display aesthetics, SEO effects, and user experience of the content.For example, a product title may display differently on different devices due to leading and trailing spaces, or a keyword list may be surrounded by additional symbols, affecting search engine recognition.

2025-11-08

How to implement automatic conversion of uploaded images to WebP format to optimize front-end loading and display speed?

In today's content operation, website loading speed is crucial for user experience and search engine rankings.Images are an important part of web content, and their loading performance is often a key factor affecting overall speed.AnQiCMS (AnQiCMS) is well aware of this and provides a convenient image optimization feature, especially converting images uploaded to WebP format automatically, which can significantly improve the display speed of the website's front-end.### WebP format: A speed booster for front-end loading WebP is an image format developed by Google

2025-11-08

How to batch regenerate all content thumbnails to fit the new frontend display size?

When the visual style of a website needs a complete overhaul, or to adapt to the ever-changing size of device displays, we often need to adjust the size of image thumbnails.AnQiCMS (AnQiCMS) fully understands this and provides a convenient and efficient solution for such needs.How to batch regenerate thumbnails for all content in response to adjustments in front-end display dimensions to ensure the aesthetic beauty and loading efficiency of the website, which is a concern for many operators.Why do you need to regenerate the thumbnail? Thumbnails play a crucial role in website operations

2025-11-08