How to determine if a value exists in an array or list in Anqi CMS template (using the `in` operator)?

Calendar 👁️ 60

As an experienced website operations expert, I know that the flexibility of template logic is crucial when building and maintaining an efficient, user-friendly website.AnQiCMS (AnQiCMS) with its powerful template engine and good support for Django template syntax, provides us with many conveniences.Today, let's delve deeply into a very common and practical scenario in template development:How to judge whether a value exists in an array or list in the AnQiCMS template (i.e.inthe function of the operator)?

In the display of dynamic content, we often need to decide whether to display a certain element or content block based on user permissions, article tags, classification attributes, and other information.At this point, it is particularly important to be able to quickly and accurately determine whether a value exists in a set.AnQiCMS's template engine provides two elegant and powerful ways to achieve this goal: direct useinand use the operator to judge, as well as utilizecontainThe filter performs more flexible detection.


I. Smart useinOperator: Intuitive and concise judgment

In the template syntax of AnQiCMS,inThe operator can be used intuitively to determine if a value is contained within another sequence (such as an array, list, or string) or if it exists as a key in a dictionary (map/object). Its syntax is very concise, usually with{% if %}Combine tags to perform conditional judgments.

Basic usage:

{% if 目标值 in 集合 %} <!-- 当目标值存在于集合中时显示的内容 --> {% endif %}

For example, suppose we have aarchiveobject (representing an article), it may have aFlagProperties used to mark the characteristics of articles, such as "top news","recommended","slideshow",and so on.These tags are usually stored in a string in the form of letter codes, for example, "hcfs" represents "top news, recommendations, slides, scrolling".We want to determine whether the current article is marked as 'recommended' (code forc)

{# 假设archive.Flag的值是 "hcs" #}
{% if "c" in archive.Flag %}
    <span class="recommend-tag">推荐</span>
{% endif %}

Ifarchive.FlagIt is a string containing multiple tags,"c" in archive.FlagCan effectively judge whether the character 'c' exists in this string.

Let's take a more general example, if we have a backend custom tag list.activeTags(It may be a string array) and want to check the article in the current loopitemof some tagitemTagwhether it is inactiveTagsIn:

{% set activeTags = ["SEO", "AnQiCMS", "教程"] %} {# 假设这是一个通过 {% set %} 或其他方式获取的数组 #}

{% for itemTag in item.Tags %} {# 假设 item.Tags 是当前文章的标签列表 #}
    {% if itemTag.Title in activeTags %}
        <span class="highlight-tag">{{ itemTag.Title }}</span>
    {% else %}
        <span>{{ itemTag.Title }}</span>
    {% endif %}
{% endfor %}

HereinOperators that make the judgment logic clear, very suitable for quick and direct value existence checks in templates.


Second,containFilter: more flexible and comprehensive options.

In addition to directinoperator, AnQiCMS also provides us with more powerful functions and a wider range of application scenarioscontainfilter.containThe filter can not only judge whether a value exists in a string or array, but also check if a key exists in a key-value pair (map) or a structure (struct). Its result will directly return a boolean value (TrueorFalse),This makes it very suitable for{% set %}to be used together with tags, storing judgment results for subsequent complex logic.

Basic usage:

{{ 集合 | contain:"目标值" }}

1. Determine if a string contains a certain keyword:

This isinOperator checks for string similarity but is presented in the form of a filter.

{# 判断文章内容描述中是否包含“CMS”这个词 #}
{% set description = "欢迎使用安企CMS(AnQiCMS)" %}
{% if description|contain:"CMS" %}
    <p>{{ description }} 中包含了“CMS”关键词。</p>
{% endif %}

2. Determine if an array contains a certain value:

This iscontainOne of the most commonly used scenarios for filters, especially when arrays are processed by other filters or tags.

{# 假设我们有一个文章分类ID的列表,并想检查当前文章的CategoryID是否在其中 #}
{% set hotCategoryIds = [1, 5, 8, 12] %}
{% if hotCategoryIds|contain:archive.CategoryId %}
    <p>当前文章属于热门分类!</p>
{% endif %}

Please note, when judging arrays,containThe filter checks whether the target value isentirely equalis located in an array element.

3. To determine whether a key exists in a key-value pair (map) or a struct:

This is ainThe operator does not directly support, butcontainThe powerful feature that the filter can easily handle. It allows us to check if an object (such as a configuration object, a custom field collection) contains a specific property or key.

AssumewebInfoIs an object or map containing website information, we want to check if it hasTitleattribute:

{# 假设 webInfo = {Title:"安企CMS", Keyword:"AnQiCMS"} #}
{% set webInfo = system.properties %} {# 比如从系统标签获取的自定义属性 #}
{% if webInfo|contain:"Title" %}
    <p>网站信息包含 Title 字段。</p>
{% endif %}

here,contain:"Title"Will checkwebInfoWhether the object or map has a key named 'Title'.


How to choose:inoperator vs.containFilter?

Both methods aim to solve the problem of 'whether the value exists in the set', but they have different focuses in practical applications:

  • SelectinOperator:

    • When you need to{% if %}within the tagdirect, conciseWhen making a boolean judgment.
    • The target collection is explicitly a string (check for substring) or a simple array/list/map (check for elements/keys).
    • Pursuing code's.Readability and expressiveness,target_value in collectionThis natural language style of writing is very intuitive.
  • SelectcontainFilter:

    • When you need to assign a judgment resultto a variableso that it can be reused in subsequent complex logic (combined with{% set %})
    • When your target collection is possiblyof multiple typesone among (string, array, map, struct) and you want to check them in a uniform way.
    • When you need to convertcontainServe as a judgeFilter chainFor example, when a part is{{ some_data | another_filter | contain:"value" }}.
    • When it needs to checkThe key name of map or structIf it exists,containThe filter is the better choice.

IV. Examples of practical application scenarios

Regardless of which method you choose, to determine whether a value exists in a set, it is widely used in AnQiCMS templates:

  1. Navigation menu highlighting:Determine if the current page URL or ID exists in the sub-list of a navigation item to add to the active navigation itemactiveClass.
  2. Content permission control:Determine whether to display paid content or hide some information based on whether the current user's group ID is in the list of group IDs allowed to access specific content.
  3. Article feature display:Based on the article'sFlagattributes (such as “Top Story”, “Recommendation”) contain a specific tag, dynamically displaying different icons or styles.
  4. Dynamic form rendering:Check if the option values of the custom field contain the value selected by the user to pre-fill the form.

MasteredinAnd operatorscontainFilter, you will be able to control the content display logic of AnQiCMS templates more flexibly and powerfully, providing users with a more intelligent and personalized website experience.


Frequently Asked Questions (FAQ)

Q1: Can I determine if a value does not exist in an array or list?

A1:Of course. You can addinthe operator beforenotthe keyword, or incontainAdd a boolean value returned by the filter before!the sign for inversion. For example:

  • Usenot in:{% if "c" not in archive.Flag %} ... {% endif %}
  • UsecontainInvert filter:{% set isContained = archive.Flag|contain:"c" %}{% if !isContained %} ... {% endif %}

Q2: If my array or list is dynamically generated, are these two methods still valid?

A2:Absolutely valid.inAnd operatorscontainFilters are designed to process dynamic data. As long as your array, list, string, or object is valid and structured correctly when rendered in the template, both methods will work normally

Related articles

How to use modulo operation to insert a specific HTML structure after every N elements in an article list?

Good, as an experienced website operation expert, I am very willing to deeply analyze how to use modulo operation in AnQiCMS to inject more vitality and functions into your article list. --- ## Advanced Anqi CMS Operations: How to skillfully use modulo operations to insert specific HTML structures after every N elements in an article list?

2025-11-06

What are some practical applications of modulo operations when implementing alternating row coloring or cyclic display in templates?

In the Anqi CMS template world, we often need to make page elements move to be more visually vibrant and organized.This is not just for beauty, but also to enhance the user's reading experience and information acquisition efficiency.In this multitude of means to achieve dynamic effects, the modulo operator (Modulo Operator) plays a seemingly basic but extremely practical role.As an experienced website operations expert, I am well aware of how to transform these technical details into operational strategies that can directly improve website performance.

2025-11-06

Can I use the modulus operator to determine if a number is a multiple of another number (the `divisibleby` filter)?

As an experienced website operations expert, I fully understand the importance of precise data judgment in managing and displaying website content.AnQiCMS (AnQiCMS) offers many conveniences for content creators with its concise and efficient Go language architecture and flexible Django-style template engine.Today, let's delve into a very useful tool in the AnQiCMS template engine - the `divisibleby` filter, which helps us elegantly solve the problem of determining whether a number is a multiple, goodbye to the complex modulo operations in the template.##

2025-11-06

How to calculate the remainder of two numbers (modulus operation `%`) in AnQi CMS template?

As an experienced website operations expert, I know that flexibility and practicality of templates are crucial when managing content systems.AnQiCMS (AnQiCMS) with its efficient features based on the Go language and syntax support similar to Django template engine, provides us with powerful content display capabilities.Today, let's delve into a very practical mathematical operation in template creation - how to calculate the remainder of two numbers, which is what we often call modulus (`%`).

2025-11-06

Can I use the `in` operator to check if a key exists in a map (key-value pair) or a structure?

## AnQi CMS template: Exploring the way to check the existence of key-value pairs and members in structures As an experienced website operations expert, I know how important it is to flexibly and effectively operate data in daily content management and website maintenance.In such a powerful content management system as AnQiCMS, which is developed based on Go language, the data processing capability at the template level directly affects the display effect and development efficiency of the front-end page.Today, let's delve into a common template operation requirement

2025-11-06

How to use the `not in` operator in the AnQi CMS template to determine if a value is not in a set?

As an experienced website operations expert, I know how important it is to flexibly control the display logic of content in daily content management.AnQiCMS with its high efficiency and customizable features provides us with a powerful template engine, which draws on the essence of Django templates, allowing us to implement complex logical judgments on the front-end page like programming.Today, let's delve into a very practical operator in content filtering and permission control - `not in`, and see how to use it in AnQiCMS

2025-11-06

How to check if a label is in a specific list when displaying different content based on user tags?

As an experienced website operation expert, I am well aware that personalization and dynamic display are the keys to improving user experience and increasing content conversion rates.AnQiCMS (AnQiCMS) has provided great convenience for us to achieve these goals with its flexible and powerful template engine.Today, let's delve into a very practical scenario in template creation: **How to check if a user tag is in a specific list when dynamically displaying different content?In Anqi CMS, we often tag articles, products, and other content with various labels, such as "New Product Recommendation"

2025-11-06

How to determine if the current document's category ID is included in the preset restricted category list?

In the daily operation of Anqi CMS, we often encounter scenarios where we need to perform different operations based on the classification of documents.For example, articles under certain specific categories may require unique layout styles, or only content from certain categories may be accessible to certain user groups.How can we accurately determine whether the classification ID of the current document is in a predefined 'restriction' or 'special processing' classification list, which has become a core issue.

2025-11-06