How does AnQiCMS determine if a string or array contains a specific keyword and display content accordingly?

Calendar 👁️ 73

In website operation, we often need to dynamically adjust the display of the page based on the specific attributes or keywords of the content.For example, when the article title contains the words 'latest', we may want to add an eye-catching 'NEW' label; or when the product description mentions 'free shipping', an icon indicating free shipping will be automatically displayed.AnQiCMS (AnQiCMS) provides powerful template functions and rich filters, making it easy to meet these needs.

This article will delve into how AnQiCMS can judge whether a string or array contains a certain keyword and display or hide content accordingly. We will focus on introducingcontainFilter and combine with actual scenarios to help you easily control dynamic content display.

Core function:containFilter - Determine if the content contains keywords

AnQiCMS template engine built-in a very practicalcontainA filter that helps us quickly determine whether a variable (whether it is a string, array, or even a struct or map key name) contains the specified keyword. This filter returns a boolean value (TrueorFalseWe can control the display logic based on this result.

containBasic usage of filters:

{{ 待检查的变量 | contain:"关键词" }}

Example one: Determine if a string contains a specific word.

Assuming you have a news article that needs to include the words 'exclusive' in the title, a 'Special' corner mark should be displayed on the page.

Firstly, we can go througharchiveDetailLabel to get the article title:

{% archiveDetail articleTitle with name="Title" %}

Then, usecontainFilter to determine if the title contains 'Exclusive':

{% if articleTitle | contain:"独家" %}
    <span class="special-badge">Special</span>
{% endif %}

This, only when the article title contains "exclusive", the "Special" corner mark will appear on the page.

Example two: judge whether there is a keyword value in the array.

The articles on the website usually have many Tag tags. Suppose we want to determine if the current article contains the "Promotion" tag, and if it does, we will display a special offer message.

We can first retrieve the list of all tags for the current article:

{% tagList tags with itemId=archive.Id limit="10" %}

tagsThe variable is now an array. Next, we can usecontaina filter to check this array:

{% if tags | contain:"促销" %}
    <p class="promo-text">🎉 购买此商品可享受限时促销优惠!</p>
{% endif %}

Please note that when checking an array,containthe filter checks whether each element in the array matchescompletely equal tothe keyword you provided. For example, iftagsthere is an element in the array that is["大促销"], and you are checking forcontain:"促销"The result will beFalseIf you need to perform fuzzy matching, you may need to convert the array elements to strings and then check for inclusion one by one, or use the method described belowsplitThe filter performs a finer processing.

Obtaining the content to be judged: diverse sources.

In AnQiCMS, you can retrieve the content that needs keyword judgment through various built-in tags. Here are some common examples:

  • Article title or content:
    
    {% archiveDetail article with name="Title" %}
    {% archiveDetail articleContent with name="Content" %}
    
  • Category name or description:
    
    {% categoryDetail categoryName with name="Title" %}
    {% categoryDetail categoryDesc with name="Description" %}
    
  • Single page content:
    
    {% pageDetail pageContent with name="Content" %}
    
  • Custom field:If you define custom fields for the content model (for exampleproduct_features), you can also directly retrieve its value for judgment.
    
    {% archiveDetail productFeatures with name="product_features" %}
    

Flexible application: build dynamic display logic

CombinecontainFilters and AnQiCMS powerfulifConditional judgment as well asforLoop, you can achieve various complex dynamic display requirements.

Scenario: Display different contact icons based on custom field content

Assuming your product detail page has a custom fieldsupport_methodUsers can fill in contact information such as "WeChat, phone, email" in the background. You want to display the corresponding contact icons based on these keywords.

  1. Get custom field content:
    
    {% archiveDetail supportMethod with name="support_method" %}
    
  2. Make a judgment and display:
    
    <div class="contact-icons">
        {% if supportMethod | contain:"微信" %}
            <a href="#" class="icon-wechat" title="微信联系"></a>
        {% endif %}
        {% if supportMethod | contain:"电话" %}
            <a href="tel:{{ contact with name='Cellphone' }}" class="icon-phone" title="电话联系"></a>
        {% endif %}
        {% if supportMethod | contain:"邮件" %}
            <a href="mailto:{{ contact with name='Email' }}" class="icon-email" title="邮件联系"></a>
        {% endif %}
    </div>
    

In this example, we also combinedcontactUse tags to obtain preset phone numbers and email addresses, making contact information more dynamic and complete.

Advanced techniques and precautions

1. Split the string into an array and then judge:splitorfieldsFilter

If one of your fields is a string containing multiple keywords, for exampletags_string = "安企CMS,建站,教程"Would you like to check if it contains 'tutorial', use it directlycontain:"教程"It may not be accurate enough due to the presence of delimiters (if the keyword is安企CMS, while the string is安企CMS入门, directlycontainwill returnTrueThis can be split into an array first:

{% set tagsArray = tags_string | split:"," %} {# 使用逗号作为分隔符 #}
{% if tagsArray | contain:"教程" %}
    <p>包含“教程”关键词</p>
{% endif %}

fieldsThe filter can split the string into an array by spaces.

2. Determine the number of times the keyword appears:countFilter

If it is not only to judge whether it exists, but also to know how many times the keyword appears, you can usecountFilter:

{% set content = "安企CMS是强大的CMS,安企CMS易于使用。" %}
{% set cmsCount = content | count:"安企CMS" %}
<p>“安企CMS”在内容中出现了 {{ cmsCount }} 次。</p>
{% if cmsCount > 1 %}
    <p>这是一个重要词汇!</p>
{% endif %}

3. Alternative solution:indexFilter

indexThe filter returns the position of the first occurrence of the keyword in the string (starting from 0). If the keyword does not exist, it returns-1. This can also be used to determine if the keyword exists:

{% set title = "安企CMS最新动态" %}
{% if title | index:"最新" != -1 %}
    <span>发现最新动态!</span>
{% endif %}

indexWhen dealing with Chinese characters, issues related to character encoding length may arise. Attention should be paid to position calculation, as a Chinese character is usually counted as 3 positions. For simple inclusion checks,containThe filter will be more intuitive and convenient.

4. Case sensitivity

String comparison in AnQiCMS templates is usually case sensitive. This meanscontain:"CMS"will not matchcms. If you need to perform a case-insensitive judgment, you can convert the string to a uniform case before judgment (for example, convert all to lowercase), and then perform the judgment:

{% set title = "AnQiCMS更新" %}
{% if title | lower | contain:"cms" %}
    <p>标题中包含不区分大小写的“cms”</p>
{% endif %}

5. Performance Consideration

Although the filter function is powerful, but using complex filters frequently in large amounts of content or loops may have a slight impact on page loading speed.Under most common scenarios, this impact is negligible, but if you encounter a performance bottleneck, consider pre-processing the data at the controller layer (Go backend) and directly passing the boolean result to the template.

Summary

AnQiCMS template filter, especiallycontainFilters, providing website operators with great flexibility, can dynamically display content based on keywords in strings or arrays. By cleverly combiningifStatement,forLooping and other auxiliary filters, you can build a highly personalized content display logic that meets user needs, thereby significantly improving the user experience and operation efficiency of the website.Master these skills and it will make your AnQiCMS website operation more proficient.


Frequently Asked Questions (FAQ)

Q1:containDoes the filter distinguish between uppercase and lowercase? How can I implement case-insensitive judgment?A1: Yes

Related articles

How to remove specific characters or spaces from a string in AnQiCMS template?

In website content management, string processing is inevitable and crucial.In order to maintain the beauty of the page, keep the standardization of data output, or for SEO optimization, we often need to make fine adjustments to text content, such as removing extra spaces, punctuation marks, or other specific characters.AnQiCMS provides a flexible and powerful template engine, allowing us to easily implement these string operations in front-end templates.

2025-11-08

How to split a string into an array by a specified separator and iterate and display it in the template in AnQiCMS?

In website operations and content management, we often encounter such scenarios: a certain field in the background stores multiple related information, such as multiple keywords of an article, various functional tags of a product, or multiple aliases of an author.This information is usually connected into a string with commas, semicolons, or other specific symbols.When it is necessary to display this information one by one or perform style processing in the website front-end template, it is necessary to split this string into independent items and then traverse and display them one by one.AnQiCMS provides a powerful and flexible template engine, its syntax style is similar to

2025-11-08

How can simple mathematical arithmetic operations be performed in the AnQiCMS template to display the result?

Handling arithmetic operations in AnQiCMS templates is an important link to the dynamic and personalized display of website data.No matter whether you need to calculate the total price of goods, display discount information, or make conditional judgments based on certain values, AnQiCMS's powerful template engine can provide flexible support.Thanks to its Django template engine features, simple mathematical arithmetic operations can be performed directly in the template without complex code logic.### Directly perform expression calculation in the template AnQiCMS template engine supports double braces `{{ }}`

2025-11-08

How to format a timestamp into the display format of "Year-Month-Day" in AnQiCMS?

In daily website operations, the display format of dates is crucial to user experience.A clear, consistent, and easy-to-understand date format that allows visitors to easily obtain information and enhance the professionalism of the website.For users of AnQiCMS, we often encounter data stored in the form of timestamps for content publishing time, update time, and so on. How to convert these long strings of numbers into a friendly display format such as 'Year-Month-Date' is an indispensable part of content presentation.

2025-11-08

How does AnQiCMS handle image resource management and optimization?

In the daily operation of websites, images are not only an important part of the content, but also a key factor affecting website performance and user experience.Efficient image resource management and optimization, can significantly improve website loading speed, improve search engine rankings, and effectively protect the copyright of original content.AnQiCMS is a system born for content operation, which provides comprehensive and practical functions in image processing to help us easily meet these challenges.### A comprehensive centralized management of image resources AnQiCMS provides a centralized management platform for image resources

2025-11-08

How to use AnQiCMS template tags to accurately control the display content of article detail pages?

The website is operational, and the article detail page is a key link for users to deeply interact with content and understand products or services.A well-designed, precise information presentation detail page, which can not only significantly improve user experience, but also effectively assist in SEO optimization.In such a flexible and efficient content management system as AnQiCMS, we can achieve fine-grained control over the content of article detail pages by ingeniously using its template tags.

2025-11-08

In AnQiCMS, how to implement dynamic pagination on the article list page and control the number of items displayed per page?

Manage website content in Anqi CMS, the article list page is usually one of the main entry points for users to browse information.To provide a smoother user experience and optimize page loading performance, it is particularly important to implement dynamic pagination and flexible control over the number of items displayed per page.AnQi CMS provides powerful and easy-to-use template tags that allow us to easily implement these features.### Core Concept: The Foundation of Dynamic Pagination and Page Size Control In Anqi CMS, the implementation of dynamic pagination for article lists mainly relies on two core template tags: 1. **`archiveList`

2025-11-08

How to customize the URL rewrite rules of AnQiCMS website to optimize search engine display effect?

In website operation, the structure of the URL (Uniform Resource Locator) plays a crucial role in search engine optimization (SEO) and user experience.A clear and meaningful URL can not only help search engines better understand the content of the page, but also enable users to have expectations of the page content before clicking, enhancing trust.AnQiCMS as a system focusing on enterprise content management, fully understands this point, and therefore provides a flexible feature for customizing pseudostatic rules.

2025-11-08