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

Calendar 👁️ 66

During the development of AnQi CMS templates, we often encounter the 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 a user tag exists in a predefined tag list;Or when handling complex business logic, determine if a permission ID exists in the current user's permission set.For this kind of requirement, AnQiCMS template engine provides a simple and powerful solution, allowing developers to handle these logic in an elegant way.

In the AnQiCMS template system, we do not need to write complex loops to compare array elements one by one. Thanks to its built-in rich filters, we can use them directlycontainThe filter can easily complete this task. This filter is designed to be very intuitive, and its core function is to determine whether an object (which can be a string, array, Map, or structure) contains a certain keyword and return a boolean value (TrueorFalse)

Deep understandingcontainFilter

containThe filter is a very practical tool in the AnQiCMS template engine, which can efficiently check whether a collection or string contains the specified content.When applied to an array (slice), it checks if there is an element value that matches the provided "keyword" exactly.The returned boolean value can be directly used for conditional judgment in the template(ifSentences), thus achieving dynamic content display.

Actual operation: How to determine if a value exists in an array (slice)?

Let's demonstrate through a specific example.containThe usage of the filter to determine if a value exists in an array (slice).

Assuming we have a variable named in the template context of AnQiCMS.user_tagsAn array that contains all the tags currently owned by the user, for example:["VIP", "推广大使", "活跃用户"]Now, we want to determine if the user has the 'VIP' tag.

{# 假设 user_tags 是一个包含用户标签的数组 #}
{% set user_tags = ["VIP", "推广大使", "活跃用户"] %}

{# 使用 contain 过滤器判断是否存在“VIP”标签 #}
{% if user_tags|contain:"VIP" %}
    <p>恭喜您,您是我们的尊贵VIP用户!</p>
    <a href="/vip-exclusive-content">查看VIP专属内容</a>
{% else %}
    <p>您还不是VIP用户,立即升级享受更多特权!</p>
    <a href="/upgrade-to-vip">升级VIP</a>
{% endif %}

In the code above:

  1. We first pass through{% set user_tags = ["VIP", "推广大使", "活跃用户"] %}Defined a nameduser_tagsAn array. In practical applications,user_tagsThis is usually passed to the template by the backend logic.
  2. Next, we use{% if user_tags|contain:"VIP" %}to make conditional judgments.user_tags|contain:"VIP"This part iscontainThe application of the filter, it will checkuser_tagsif there is a string in the array"VIP".
  3. If it exists, the condition judgment result isTrueIt will then display content such as 'Congratulations, you are our esteemed VIP user!'.
  4. If it does not exist, the condition judgment result isFalseThis will display content such as 'You are not a VIP user...' etc.

This approach avoids the麻烦 of manually traversing the array, making the template code more concise, readable, and efficient.

It is not just an array:containThe extensive application scenarios of filters

containThe filter is not only effective for arrays (slice), but its strength lies in its broad applicability. It can be applied to various data types to meet different judgment needs:

  • Determine if a string contains a substring:You can check if a longer text string contains a specific keyword.
    
    {% set article_title = "安企CMS:打造高效内容管理体验" %}
    {% if article_title|contain:"CMS" %}
        <p>标题中包含关键词“CMS”。</p>
    {% endif %}
    
  • Determine if a Map or structure contains a specific key name: containThe filter can also be used to check if a Map (key-value set) or structure contains a specified key name (key).
    
    {% set product_info = {"name": "安企CMS", "version": "3.0", "price": 0} %}
    {% if product_info|contain:"version" %}
        <p>产品信息中包含版本号。</p>
    {% endif %}
    
    It should be noted that when used with Map or structure,containThe check is whether the key name (key) exists, not whether a value (value) exists in any key of the Map.

Summary

AnQiCMS template engine'scontainThe filter brings great convenience to template development. It provides a declarative, efficient, and easy-to-understand way to determine whether a specific content exists in an array (slice), string, Map, or struct.By flexible usecontainThe filter, we can write more dynamic, logical and stronger AnQiCMS templates, thus enhancing the website's interactive experience and the efficiency of content operation.


Frequently Asked Questions (FAQ)

Q1: How to determine if an array does not contain a specific value? A1:If you want to determine if an array does not contain a specific value, just add in front ofcontainthe filter's resultnotthe keyword.

{% set user_roles = ["Admin", "Editor"] %}
{% if not user_roles|contain:"Guest" %}
    <p>用户不是访客。</p>
{% endif %}

Q2: Can I also get the specific 'position' of this value in the array besides checking for its existence? A2:Yes. You can use the AnQiCMS template engine provided.indexA filter to get the first occurrence position of a value in an array (slice) or string. If not found, it will return-1.

{% set product_ids = [101, 105, 110, 105] %}
{% set position = product_ids|index:105 %}
<p>值105在数组中首次出现的位置是:{{ position }}</p> {# 输出:1 (数组索引从0开始) #}

{% set not_found_position = product_ids|index:999 %}
<p>值999在数组中首次出现的位置是:{{ not_found_position }}</p> {# 输出:-1 #}

Q3: If there may be multiple identical values in an array, how can I know how many times it appears? A3:You can usecountA filter to count the number of times a specific value appears in an array (slice) or string.

{% set status_list = ["pending", "approved", "rejected", "approved"] %}
{% set approved_count = status_list|count:"approved" %}
<p>“approved”状态出现了:{{ approved_count }} 次。</p> {# 输出:2 #}

{% set article_text = "AnQiCMS 是一个强大的CMS,AnQiCMS让内容管理更简单。" %}
{% set cms_count = article_text|count:"CMS" %}
<p>“CMS”在文本中出现了:{{ cms_count }} 次。</p> {# 输出:2 #}

Related articles

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

How to quickly judge whether a string of text in the AnQiCMS template contains specific sensitive words?

In website content operation, compliance and security are of great importance.Especially for platforms with user-generated content (UGC) or when publishing articles, product information, we often need to quickly determine if a string of text contains specific sensitive words.AnQiCMS is an efficient enterprise-level content management system that also provides very flexible and convenient tools at the template level, allowing you to easily meet this requirement.

2025-11-07

How to display the links and titles of the previous and next related articles on the document detail page of Anqi CMS?

In Anqi CMS, adding links and titles of "Previous Article" and "Next Article" to the document detail page is a very practical feature to enhance user experience and content consistency.This not only encourages users to browse more content, but also helps optimize the internal links of the website.AnQi CMS provides simple and efficient template tags, allowing us to easily meet this requirement.

2025-11-07

How to use the `archiveFilters` tag to add advanced filtering functionality to the document list of AnQi CMS?

Manage content in Anqi CMS, especially when the website content becomes rich, how to help visitors quickly find the information they need has become the key to improving user experience.If your website offers a diverse range of products or services, or contains a large number of articles with different attributes, then an efficient filtering function will be essential.Today, let's delve into a very useful tag in Anqi CMS, `archiveFilters`, which helps us easily add advanced filtering features to the document list.The foundation of the flexible content model

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

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

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

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 has become the key to achieving fine-grained control.

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