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:
Select
inOperator:- 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.
- When you need to
Select
containFilter:- 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 convert
containServe 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.
- When you need to assign a judgment resultto a variableso that it can be reused in subsequent complex logic (combined with
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:
- 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 item
activeClass. - 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.
- Article feature display:Based on the article's
Flagattributes (such as “Top Story”, “Recommendation”) contain a specific tag, dynamically displaying different icons or styles. - 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:
- Use
not in:{% if "c" not in archive.Flag %} ... {% endif %} - Use
containInvert 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