How to use the `contain` filter in AnQiCMS template to determine whether a string or an array contains a specific keyword?

Calendar 👁️ 72

During the process of building a website with AnQiCMS, flexibly displaying information according to content characteristics is the key to improving user experience and operational efficiency. To achieve this, the system has built-in many practical template filters, among whichcontainThe filter is a powerful tool for determining if content contains specific keywords.

It can help you match content directly at the template level without modifying the backend code, thereby making your website content display more intelligent and personalized.

What iscontainFilter?

containThe filter is a very practical built-in feature of the AnQiCMS template system, which can determine whether a string, an array (usually a slice in Go), a key-value pair (Map), or even a structure (Struct) contains the specific keyword you are looking for.

Its core function is to perform an 'inclusivity' check. When the target content indeed contains the specified keywords,containthe filter will return a boolean valueTrueIf not found, it will returnFalseThis simple and clear return mechanism allows you to easily perform various conditional judgments and logical controls in the template.

Basic usage: Determine if a string contains a keyword

The most common scenario is to determine whether a text string contains a certain keyword. For example, you may want to check if an article title or abstract mentions a hot topic.

Assuming we have a description of anq CMS, want to know if it mentions "CMS":

{# 直接判断字符串中是否包含“CMS” #}
<p>这段文字是否包含“CMS”?
    {% if "欢迎使用安企CMS(AnQiCMS)"|contain:"CMS" %}
        <span>是,包含!</span>
    {% else %}
        <span>否,不包含。</span>
    {% endif %}
</p>

After this code is executed, the page will display “Yes, it contains!” because the string indeed contains the word “CMS”. It is worth noting that,containThe filter is case-sensitive, if you search "cms", the results may beFalsedepending on the specific wording of the original text.

Combinesettags to implement more flexible logic control

In practice, we usually do not write long strings directly in conditional statements. The more common way is to check the content of the variable orcontainThe result of the filter is stored so that it can be used in complex template logic. At this time,setlabels can be put to use.

For example, we want to display a special mark based on whether the article title contains 'tutorial':

{# 假设archive.Title是当前文章的标题 #}
{% set article_title = archive.Title %}
{% set is_tutorial = article_title|contain:"教程" %}

<h1 class="article-title">{{ article_title }}</h1>

{% if is_tutorial %}
    <span class="tag-tutorial">【教程】</span>
{% endif %}

<p>文章内容...</p>

BysetLabel, we willcontainAssign the judgment result tois_tutorialVariable, so that this judgment result can be reused anywhere in the template without having to recalculate it each time.

Advanced Application: Determine if an array or slice contains a specific value

containThe power of the filter is not limited to strings. It also comes into play when you need to determine if a collection (such as the array or slice commonly used in AnQiCMS) contains a specific element.

Suppose your article has multiple tags (Tag), stored in an array, and you want to check if it contains the tag "SEO optimization":

{# 假设tags_list是通过|list过滤器从字符串转换而来的数组,或者直接是后端传来的数组 #}
{% set tags_list = '["安企CMS", "内容管理", "SEO优化", "多站点管理"]'|list %}

<p>文章标签列表:
    {% for tag in tags_list %}
        <span class="article-tag">{{ tag }}</span>
    {% endfor %}
</p>

{% if tags_list|contain:"SEO优化" %}
    <p class="seo-info">这篇文章与SEO优化相关,快来学习吧!</p>
{% else %}
    <p>这篇文章不包含SEO优化标签。</p>
{% endif %}

In this case,containThe filter will check each element in the array one by one to see if there is a value that matches 'SEO optimization' exactly.

Further: Determine if a specific key name exists in key-value pairs or structures.

other than strings and arrays,containThe filter can handle more complex data types, such as key-value pairs (map) or Go language structs. However, there is an important detail to note: in this scenario,containThe filter is to determine whether it exists in these data structuresSpecify the key (key) with the name, not to determine whether someValueexists in the values corresponding to these keys.

For example, you have a product detail key-value pair, want to check if it contains the key 'price' to decide whether to display the price information:

{# 假设product_details是一个键值对或结构体 #}
{% set product_details = {'name': '安企CMS企业版', 'price': 999, 'features': ['多站点', 'SEO']} %}

<p>产品名称:{{ product_details.name }}</p>

{% if product_details|contain:"price" %}
    <p>产品价格:<strong>¥{{ product_details.price }}</strong></p>
{% else %}
    <p>该产品暂无公开价格。</p>
{% endif %}

here,product_details|contain:"price"Will checkproduct_detailsif there exists a key namedpriceThe key. If it exists, it is returnedTrue, Display the price. This is very useful for dynamically displaying different attributes of different types of products or content

Practical application examples: Make the website content smarter

containThe flexible use of filters can bring many practical benefits:

  1. Dynamic recommendations and identificationIf the article title contains keywords such as 'hot' or 'new', it can dynamically display 'HOT' or 'NEW' badges to attract user clicks.
  2. Personalized content display:According to the name of the article category, dynamically load different advertisements, recommendation modules, or styles.
  3. User permission control (combined with user group tags)If you use the AnQiCMS user group management, you can determine whether the current user's tag (Tag) contains 'VIP', thus deciding whether to display VIP exclusive content or download links.
  4. Content Highlight and FilteringIn the search results page, if the search term appears in the article abstract, it can be highlighted; or judge whether the content attribute contains the corresponding value according to the user's selected filter conditions.
  5. Template style dynamic switching: Some page elements may need to adjust CSS styles based on whether their title contains specific words, for example, navigation items with titles containing 'contact' may have special icons added.

Whether it is a simple text match or complex array and data structure judgment,containFilters are all designed with intuitive usage, bringing great flexibility and control to the content presentation of AnQiCMS. Master it, and your website operation will become more efficient and intelligent.


Frequently Asked Questions (FAQ)

1.containIs the filter case sensitive?Yes,containThe filter is case sensitive when matching keywords.For example, if you search for “CMS”, then “cms” or “Cms” will not be matched.If you need to perform a case-insensitive match, you can consider using it before matchinglowerorupperThe filter converts the string to uppercase or lowercase before matching.

2.containCan the filter determine a certain key-value pair (map) or structValueDoes it exist?Cannot. WhencontainThe filter is used when checking key-value pairs or structures, it will only judge whether the specifiedkey name (key)While it will not check whether a particular content is included in the values corresponding to these keys. If you need to check whether a value exists in a structure or a field of a key-value pair, you must first obtain the value of the field, and then use that value tocontaina filter. For example:{{ product_details.name|contain:"企业" }}.

3. If I want to judge multiple keywords,containHow do I use the filter?If you need to judge whether the target content contains multiple keywords amongany one of them(OR logic), orallKeywords (AND logic), can be combined with multiplecontainFilters andifLogical judgments to achieve.

  • Example of OR logic:{% if article.Title|contain:"教程" or article.Title|contain:"指南" %}
  • Example of AND logic:{% if article.Title|contain:"安企" and article.Title|contain:"教程" %}You can flexibly apply according to your actual needsand/orThese logical operators are used to build more complex judgment conditions.

Related articles

How to retrieve and display a list of documents under a specified Tag, and support pagination?

In website content management, categorizing and displaying documents according to their tags (Tags) is an important strategy to enhance user experience and content discoverability.AnQiCMS provides a set of intuitive and powerful template tags that help us easily achieve this goal, while also supporting flexible pagination functionality, even when faced with massive amounts of content, it can maintain the page's cleanliness and loading speed.

2025-11-07

How to display a multi-level nested category list in AnQiCMS, such as top-level categories and their subcategories?

When building a website, a clear and organized content structure is the foundation for improving user experience and search engine optimization.Especially for content-rich websites, how to efficiently display multi-level nested category lists, such as top-level categories and their subcategories, is a concern for many operators.AnQiCMS is a flexible enterprise-level content management system that provides intuitive and powerful template tags, allowing you to easily meet this requirement.

2025-11-07

How to get and display the detailed information of the current category in AnQiCMS template, such as title, description, thumbnail, and Banner group image?

Building a website in AnQiCMS, especially when we need to present rich and accurate information on category pages, it is particularly important to deeply understand how to obtain detailed data of the current category in templates.This is not just for aesthetics, but also to provide a better user experience and search engine optimization.The AnQiCMS template system is designed to be very flexible and easy to use, it uses syntax similar to the Django template engine.

2025-11-07

How does AnQiCMS implement different content display and adaptation for PC and mobile devices through the template directory structure?

In the era when mobile internet occupies a dominant position, ensuring that website content can be perfectly displayed on different devices is a core issue that every website operator is very concerned about.AnQiCMS provides an extremely flexible and powerful solution in this aspect, allowing us to easily provide optimized display and interaction experience for users on both PC and mobile terminals.The key to AnQiCMS achieving content adaptation for PC and mobile ends lies in its carefully designed template directory structure and flexible website mode selection.

2025-11-07

How to use the `length` filter to get the length of a string, array, or key-value pair for display or judgment

In website content operation, we often encounter scenarios where we need to obtain or judge the length of data.For example, displaying the number of words in an article, the number of items in a list, or deciding whether to display an element based on the content length.AnQiCMS's template engine provides a series of practical filters to help us meet these needs, among which the `length` and `length_is` filters are the best.They can help us easily achieve these functions, making the dynamic display and interaction logic of the website more flexible.

2025-11-07

How to display a custom SEO title on the article detail page instead of the article title?

In content operation, setting the title of the website article detail page is a key link.We often encounter such situations: the content title of the article itself needs to be eye-catching and creative, in order to attract readers' clicks;And the page title required for search engine optimization (SEO) (i.e., the content of the `<title>` tag displayed on the browser tab), is more focused on keyword layout, length control, and search engine friendliness.In AnQiCMS, you can fully flexibly manage these two different titles to ensure both user experience and SEO effectiveness.

2025-11-07

How to configure URL rewrite rules in Anqi CMS to optimize search engine crawling?

In website operation, Search Engine Optimization (SEO) plays a crucial role, and a friendly URL structure is a key factor in improving the performance of a website in search engines.A clear and meaningful URL not only helps search engines better understand the content of the page, but also allows visitors to see the theme of the page at a glance, enhancing the user experience.Traditional dynamic URLs often contain parameters that are difficult to understand, which is not friendly to SEO and users.Fortunately, AnQi CMS provides a powerful static rule configuration function, allowing you to easily optimize the URL structure of your website.

2025-11-07

How to display the multi-language content switch button on the website front end?

On AnQiCMS, it is crucial to display a multilingual content switch button on the website front-end to expand the global user base and enhance the user experience.AnQiCMS with its powerful multilingual support and flexible template mechanism makes implementing this feature intuitive and efficient. ### AnQiCMS multilingual mechanism overview AnQiCMS considered the needs of global content publishing from the outset.Its multilingual support is centered around the "multi-site management" feature.This means that you can create different sites to represent different language versions. For example

2025-11-07