How to store the judgment result of the `contain` filter in a variable for subsequent complex logic judgment?

Calendar 👁️ 71

In AnQi CMS template development, we often need to dynamically display or hide certain elements based on specific content conditions, or execute different logical branches.It is straightforward to output the result of a judgment directly in a template, but when you need to perform more complex logical branches based on this judgment, direct output seems inadequate.At this point, storing the judgment result in a variable becomes the key to achieving fine-grained control.

AnQi CMS provides powerful functionscontainA filter that helps us determine whether a string, array, or key-value pair contains specific content. After the filter performs the judgment, it will return a boolean value (TrueorFalse),perfectly fits the need for subsequent complex logical judgment.

UnderstandingcontainFilter

First, let's understandcontainthe basic usage of the filter.containThe filter's role is to check whether a target object (which can be a string, array, key-value pair, or structure) contains the specified 'keyword'. Its basic syntax is{{obj|contain:关键词}}.

For example, if you want to check if the text contains the word “AnQiCMS”:

{{"欢迎使用安企CMS(AnQiCMS)内容管理系统"|contain:"AnQiCMS"}}

This code will output directlyTrueBecause it found "AnQiCMS" in the string.

tocontainThe judgment result is stored in a variable

When we need to basecontainthe judgment result further operation, just output directly.TrueorFalseIt is not enough. At this time, the Anqi CMS template engine providessetthe tag comes into play.settags allow us to declare and assign variables in the template, we cancontainThe judgment result of the filter is assigned to this variable.

Here is an example of syntax:

{% set 变量名 = 表达式 %}

CombinecontainYou can store the judgment result of the filter in the variable like this:

{% set content_string = "安企CMS是一款基于Go语言开发的企业级内容管理系统。" %}
{% set has_go_keyword = content_string|contain:"Go语言" %}

Now,has_go_keywordThis variable stores a boolean value. Ifcontent_stringIf it contains “Go language”, thenhas_go_keywordThe value isTrueOtherwise, it isFalse.

Use variables to make complex logical judgments

OncecontainThe judgment result is stored in a variable, and we can combine it with the Anqicms template'sifLogical judgment tag, to implement more refined condition control.

Continuing with the above example:

{% set content_string = "安企CMS是一款基于Go语言开发的企业级内容管理系统。" %}
{% set has_go_keyword = content_string|contain:"Go语言" %}

{% if has_go_keyword %}
    <p>这段内容提到了Go语言,可能是一篇技术类文章。</p>
{% else %}
    <p>这段内容没有提及Go语言,可能是通用性文章。</p>
{% endif %}

This code will be based onhas_go_keywordThe value, selectively displays different paragraphs. If the content contains 'Go language', the first paragraph of text will be displayed; otherwise, the second paragraph will be displayed.

This is just a simpleif-elseExample, you can build a more complex structure according to your actual needs.if-elif-elseOr you can combine this variable with other conditions for judgment.

Application scenario expansion

tocontainThe ability to store results in variables can significantly improve the flexibility and maintainability of templates in various scenarios:

  1. Dynamic content display module:Assuming your article detail page needs to display different sidebar advertisements or recommended content based on whether the content contains specific keywords (such as "product review","new product launch"), you can first usecontainJudge, then store the result in a variable, and use it againifTo control the display of the module.

    {% set article_title = archive.Title %} {# 假设 archive.Title 是当前文章标题 #}
    {% set is_review_article = article_title|contain:"评测" %}
    
    {% if is_review_article %}
        <div class="sidebar-promo">
            <h4>最新评测产品推荐</h4>
            {# ... 显示评测相关的推荐内容 ... #}
        </div>
    {% endif %}
    
  2. Filter list data:In a custom list (for examplearchiveListIn the loop, you may want to make additional judgments on each item, such as only displaying documents whose titles do not contain "Expired".

    {% archiveList archives with type="list" limit="10" %}
        {% for item in archives %}
            {% set is_expired = item.Title|contain:"已过期" %}
            {% if not is_expired %}
                <li><a href="{{item.Link}}">{{item.Title}}</a></li>
            {% endif %}
        {% endfor %}
    {% endarchiveList %}
    
  3. Check the existence or specific value of a custom field:AnQi CMS supports custom content model fields. Sometimes, you may need to judge a specific custom field (such asproduct_featuresDoes it exist, or does its value contain a specific attribute?containA filter can be used to check key-value pairs (map) or structures (struct) for the existence of a specific key name.

    {% archiveParams custom_params with id=archive.Id sorted=false %} {# 获取文章的自定义参数 #}
    {% set has_features_field = custom_params|contain:"product_features" %}
    
    {% if has_features_field %}
        <p>产品特性:{{custom_params.product_features.Value}}</p>
    {% else %}
        <p>该产品未配置特性信息。</p>
    {% endif %}
    

    here,custom_params|contain:"product_features"It is judging whethercustom_paramsThismapDoes it exist namedproduct_featureskey?

By usingcontainThe judgment result of the filter is stored in the variable, which not only makes the template logic clearer, but also provides a powerful tool for implementing the dynamic and intelligent content display of the safe CMS website.This method avoids repeated judgment logic, improves the reusability and readability of the template, and allows your content operation strategy to be implemented more flexibly.


Frequently Asked Questions (FAQ)

  1. containIs the filter case sensitive?Yes, according to the default string handling mechanism of Go language,containthe filter is usually case sensitive. For example,"AnQiCMS"|contain:"cms"will returnFalseIf you need to perform case-insensitive judgment, you may need to performcontainBefore making a judgment, first convert the target string and keywords to the same case (for example, both to lowercase) and then compare them.

  2. exceptsetTags, there are also other ways to convertcontainDoes the result store in the variable?The AnQi CMS template engine also supportswithtags to define variables, usually used toincludeTags can pass local variables or declare temporary variables within a certain code block. AlthoughwithTags can also be used to storecontainthe result, butsetTags are usually more concise and commonly used for global or local variable assignment in templates. For example:{% with my_result = "string"|contain:"keyword" %}...{% endwith %}.

  3. containCan filters be used to judge numeric or boolean values? containThe filter is mainly used to determine whether a string contains a substring, or whether a specific element or key name exists in an array/slice, key-value pair, or structure.It does not directly determine whether the type of the variable itself is numeric or boolean, nor is it directly used for comparison of numeric or boolean values.ifTags can be used with comparison operators (such as==/>/<To be performed. For example:{% if archive.Views > 1000 %}.

Related articles

What is the difference in the judgment logic of the `contain` filter when processing Chinese string and English string?

In AnQi CMS template design, we often use various filters to process and judge data.Among them, the `contain` filter is a very practical tool that can help us quickly determine whether a text, array, or object contains specific keywords.Many users may be curious about whether there is a difference in the judgment logic of the `contain` filter when processing Chinese and English strings.

2025-11-07

Can `contain` filter be used in AnQiCMS template to check if a key exists in a map or struct?

In Anqi CMS template development, flexible handling of data structures is the key to dynamic content display.When we need to determine whether a complex data type, such as a key-value pair (map) or a structure (struct), contains a specific key name, the built-in `contain` filter provides a convenient and efficient solution.

2025-11-07

How to determine if a specific value exists in an array (slice) while developing an AnQi CMS template?

During the development of Anqi CMS templates, we often encounter scenarios where we need to determine whether an array (slice) contains a specific value.For example, you may need to dynamically adjust the display of content based on whether the user tag exists in a predefined tag list;Or when handling complex business logic, determine whether a permission ID exists in the current user's permission set.For this requirement, AnQiCMS template engine provides a concise and powerful solution, allowing developers to handle these logic in an elegant way.In the AnQiCMS template system

2025-11-07

How to use the `contain` filter to check if the user's input text contains the preset brand name?

In daily website content operations, we often need to standardize the management of user input or content generated by the system, especially when it involves brand names.Maintaining the consistency and accuracy of the brand name is crucial, not only for enhancing the brand image, but also for the SEO performance of the website, legal compliance, and user experience.AnQi CMS provides a flexible and powerful template engine, where the `contain` filter is a very practical tool that can help us efficiently check if the text contains the preset brand name.Why check the brand name in the content

2025-11-07

When do you need to judge whether multiple keywords exist in a string, does the `contain` filter have a batch processing mechanism?

In the daily operation of website content, we often encounter such a scenario: we need to judge whether a document, a page title, or any text content contains multiple keywords that we have preset.For example, we might want to know if an article mentions both 'AnQi CMS' and 'Content Operation', or at least mentions 'Go language' or 'High performance'.At this time, many friends will naturally think of the powerful `contain` filter in the AnQiCMS template engine.Then, when you need to judge whether multiple keywords exist in a string

2025-11-07

In the AnQiCMS template, can the `contain` filter flexibly configure case-sensitive keywords?

AnQiCMS provides a rich set of filters in templates for data processing and display, where the `contain` filter is a practical tool frequently used to determine if the content includes specific keywords.When using such filters, we often encounter issues related to case sensitivity, which directly affects the accuracy of search and filtering results.

2025-11-07

How to count the total number of times a specific keyword appears in the content of AnQiCMS articles?

In content operation, the reasonable layout and statistics of keywords are an indispensable part of optimizing search engine performance and improving user experience.A precise keyword distribution can not only help search engines better understand your content, but also allow users to find the information they need faster.AnQiCMS (AnQiCMS) relies on its powerful template engine to provide us with a flexible way to count the occurrences of specific keywords in article content, thereby assisting our content strategy.

2025-11-07

The `count` filter is it for exact match or partial match when calculating the number of occurrences of a value in an array?

In Anqi CMS template development, the `count` filter is a very practical tool that can help us easily count the number of times a specific value appears.However, when using this filter, many users may wonder: when it calculates the number of times a value appears, is it performing an exact match, or a more flexible partial match?The answer is not one-size-fits-all, but varies depending on the data type.

2025-11-07