The `contain` filter how to determine if a string or array contains a specified keyword?

Calendar 81

In AnQi CMS template development, flexibly controlling the display of content is the key to improving website user experience and operational efficiency.Sometimes, we may need to determine whether a piece of text, a list (array), or a data object (Map/Struct) contains a specific keyword or attribute.containThe filter can really shine, it can help us easily achieve this conditional judgment, making the template logic more intelligent.

containWhat is a filter?

In simple terms,containA filter is a very practical tool, its main function is to help us judge whether a string, array (known as Slice in Go language), key-value pair (Map) or structure (Struct) contains the keyword or key name we specify. Its judgment result will directly return a boolean value: if found, it isTrueIf not found, it isFalseThis allows us to dynamically adjust the way content is displayed based on these judgment results.

How to usecontainFilter?

containThe use of the filter is very intuitive. Its basic syntax is:

{{ obj|contain:关键词 }}

HereobjRepresents the variable you want to check, which can be a string, an array, a key-value pair, or a structure. And关键词is what you want to find inobj.

Next, let's delve into several common scenarios to gain a deeper understandingcontainThe actual application of filters.

Scenario one: Determine if a keyword exists in a string

In many cases, we may need to decide whether to display special markings based on whether the text content of article titles, product descriptions, etc. contains specific words.

For example, if you want to search for the word "CMS" in the title of an article:

{% set articleTitle = "欢迎使用安企CMS(AnQiCMS)" %}
{{ articleTitle|contain:"CMS" }}
{# 显示结果为 True #}

This boolean value can be used directly forifa statement to achieve dynamic content display:

{% set articleTitle = "安企CMS模板开发指南" %}
{% if articleTitle|contain:"CMS" %}
    <span style="color: blue;">[CMS相关]</span>
{% endif %}
<h1>{{ articleTitle }}</h1>
{# 如果 articleTitle 包含“CMS”,则会在标题前显示蓝色“[CMS相关]”标签。 #}

This usage can help you automatically add promotional tags to products containing the phrase "Limited Time Offer" on the product list page, or add醒目标识to the titles containing "Latest News" in the article list.

Scene two: Determine if an element exists in an array (list)

When you have a list of tags, category names, or other data sets,containThe filter can help you quickly check if a specific value exists in this list.

Suppose you have a list of article tags:

{% set articleTags = ["Go语言", "CMS", "SEO优化", "模板开发"] %}
{{ articleTags|contain:"CMS" }}
{# 显示结果为 True #}

{{ articleTags|contain:"Python" }}
{# 显示结果为 False #}

You can use this feature to add additional function buttons or styles to articles containing specific tags:

{% set articleTags = ["Go语言", "CMS", "SEO优化"] %}
{% if articleTags|contain:"SEO优化" %}
    <p>这篇文章包含了“SEO优化”标签,可能对SEO策略有帮助!</p>
{% endif %}
{# 如果 articleTags 包含“SEO优化”,则会显示提示信息。 #}

This method is very suitable for permission control (for example, only VIP group IDs in a specific list can access), dynamic filtering, or displaying relevant content based on user preferences.

Scene three: Determine if an object (key-value pair/structure) contains a specific key name

When processing data objects retrieved from the backend, you sometimes need to check if the object contains a specific property (key name) rather than the value of the property.containThe filter applies here as well, but it checks if the 'key name' exists in the object.

For example, you have an article object that contains title and author information:

{% set articleInfo = {Title:"安企CMS深度解析", Author:"运营小A", Views:1200} %}

{{ articleInfo|contain:"Author" }}
{# 显示结果为 True #}

{{ articleInfo|contain:"Category" }}
{# 显示结果为 False #}

This feature is very useful when it is necessary to dynamically render forms or information blocks based on data models. For example, you may only display the author information when the article object containsAuthorthe key:

{% set articleInfo = {Title:"安企CMS深度解析", Author:"运营小A"} %}
{% if articleInfo|contain:"Author" %}
    <p>作者: {{ articleInfo.Author }}</p>
{% else %}
    <p>作者信息暂无。</p>
{% endif %}

This flexibility allows you to better handle changes in the background data structure, avoiding errors in the template due to the lack of a field.

WhycontainIs the filter so important?

containThe filter plays an important role in the content operation of Anqi CMS, it allows your website content to show higher flexibility and dynamics:

  • Personalized displayBased on the specific attributes or keywords of the content, provide users with more accurate and personalized information.
  • Enhancing user experienceThrough conditional judgment, dynamically load or hide page elements to make the interface cleaner and focus on information.
  • Simplify template logic:Avoids complex string operations or background judgments, completing simple conditional logic directly in the template layer, improving development efficiency.
  • Reduce maintenance costsWhen the content strategy adjusts or the data field changes, only a small amount of template code needs to be modified to adapt, without delving into the backend.

MastercontainThe filter means you have the ability to fine-tune content control in Anqi CMS templates, allowing you to more efficiently implement various complex display requirements, making your website more competitive.


Frequently Asked Questions (FAQ)

1.containDoes the filter distinguish between uppercase and lowercase when making judgments?Yes,containThe filter is case-sensitive when matching string and array values. For example,"AnQiCMS"|contain:"cms"It will returnFalsewhile"AnQiCMS"|contain:"CMS"Then it will returnTrueIf you need a case-insensitive search, you can use it beforecontainConvert the string to a uniform case (for example, all lowercase) before making the judgment.

2. I can usecontaina filter to check if multiple keywords (such as 'KeywordA' and 'KeywordB') exist in a string or array?? containThe filter can only judge one keyword at a time. If you need to check multiple keywords at the same time, you can combine multiple filterscontainThe filter and logical operators (such asandoror)to construct more complex conditions. For example:

{% set text = "安企CMS是一个强大的系统" %}
{% if text|contain:"安企" and text|contain:"CMS" %}
    <p>同时包含了“安企”和“CMS”。</p>
{% endif %}

3. If I try to usecontainWhat would a filter return for an empty string or an empty array?Whenobjis an empty string, empty array or empty object when,containthe filter will always returnFalseIt cannot find any specified keywords or key names. In actual applications, you may need to use it first.if objorif obj|length > 0To judgeobjIs it empty to avoid unnecessary judgments, making the code logic more robust.

Related articles

How `length` and `length_is` filters are used to check the length of a string, array, or map?

In Anqi CMS template development, flexible handling and displaying data is the key to improving website interactivity and user experience.Understanding how to efficiently detect the length of strings, arrays, or mappings (similar to dictionaries or associative arrays in other programming languages) is the foundation for content operations and template customization.This article will introduce in detail the `length` and `length_is` practical filters in the Anqi CMS template engine, which will help you better control the display of page content.### `length` filter

2025-11-07

How `default` and `default_if_none` filters set a default display value for possibly empty variables?

In website content management, we often encounter situations where variable values may be empty.These empty values, if displayed directly on the front-end page, may lead to incomplete content display, page layout disorder, and even a bad user experience.AnQiCMS (AnQiCMS) as a powerful content management system, the Django template engine syntax it adopts provides us with a flexible way to handle such issues.

2025-11-07

How does the `add` filter work for adding numbers or concatenating strings in templates?

In AnQi CMS template design, we often need to perform some simple data processing, such as adding several numbers to display the total sum, or combining different text fragments into a complete sentence.At this time, the `add` filter is particularly convenient, as it is like a universal connector, capable of handling everything from arithmetic operations on numbers to the combination of text, making your template more flexible and dynamic.

2025-11-07

How do the `removetags` and `striptags` filters remove specific or all HTML tags from HTML content?

In Anqi CMS, when managing website content, we often encounter such situations: articles imported from outside, comments submitted by users, or code generated by rich text editors may contain various HTML tags.These tags are sometimes necessary, but more often, they may disrupt the page layout, introduce unnecessary styles, and even pose potential security risks. 幸运的是,AnQiCMS provides two very practical template filters —— `removetags` and `striptags`

2025-11-07

How does the `count` filter count the occurrences of a specific keyword in a string or array?

In AnQi CMS template development, efficiently handling and analyzing content is the key to enhancing website interactivity and information display capabilities.Sometimes, we need to know how many times a specific word appears in a piece of text, or how many times a specific element is included in a data list.This is when the `count` filter comes into play.It is a very practical tool that can help us quickly count the occurrences of a specific keyword in a string or an array (slice).

2025-11-07

How does the `stringformat` filter output values of different data types in a custom format?

In the AnQiCMS template, mastering the format of data output is the key to content presentation.In order to display various data types (whether it is numbers, text, or more complex structures) in the way you expect to your visitors, AnQiCMS provides a powerful and practical tool - the `stringformat` filter.It is like a precise converter that can convert different types of values according to the rules you define, outputting neat and uniform strings.### Deep Understanding of `stringformat`

2025-11-07

How does the `thumb` filter quickly generate and display a thumbnail version of the original image URL?

In website operation, images are key elements to attract users and enrich content, but large image files often slow down page loading speed, affecting user experience and search engine optimization.Anqi CMS knows this and therefore provides a very convenient and efficient solution——the `thumb` filter.It can easily convert the original image into a thumbnail version suitable for web display, without manual processing, greatly enhancing the efficiency of content publication and the overall performance of the website.### Core Function Analysis: `thumb` Filter's Working Principle This is named

2025-11-07

How does AnQiCMS adaptively display website content for different devices (PC/Mobile end)?

In today's parallel network environment of multiple devices, users may access websites through desktop computers, laptops, tablets, or smartphones.Therefore, ensuring that the website content displays well on different devices and provides a smooth user experience is a key link in the success of website operation.AnQiCMS as an enterprise-level content management system fully considers this requirement and provides a flexible and diverse adaptive display scheme for device content, allowing users to choose the most suitable method according to their own situation.AnQiCMS mainly provides three core strategies for handling multi-device display of website content

2025-11-07