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