As an experienced website operations expert, I know that flexibility in template logic is crucial when building and maintaining a high-efficiency, user-friendly website.AnQiCMS (AnQiCMS) provides many conveniences for us with its powerful template engine and good support for Django template syntax.How to judge whether a value exists in an array or list in 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.This is particularly important as it allows for quick and accurate judgment of whether a value exists in a set.inoperator for judgment, as well as usingcontainFilter for more flexible detection.
I. Smart UseinOperator: Intuitive and concise judgment
In AnQiCMS template syntax,inThe operator can be used intuitively to determine whether a value is contained within another sequence (such as an array, list, or string), or whether a key exists in a dictionary (map/object). Its syntax is very concise, usually with{% if %}Label combination usage, for conditional judgment.
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 NewsThese tags are usually stored in a string in the form of letter codes, for example, “hcfs” represents “Headlines, Recommendations, Slides, Scrolling”.c).
{# 假设archive.Flag的值是 "hcs" #}
{% if "c" in archive.Flag %}
<span class="recommend-tag">推荐</span>
{% endif %}
Ifarchive.FlagIs a string containing multiple tags,"c" in archive.FlagIt can effectively judge whether 'c' exists in this string.
Let's take a more general example, if we have a custom tag list on the back endactiveTags(possibly a string array), and want to check the current loop articleitemof 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 %}
Here are theinOperator that makes the judgment logic clear at a glance, very suitable for quick and direct value existence check in templates.
Second,containFilter: more flexible and comprehensive choices
In addition to the directinOperator, AnQiCMS also provides more powerful functions and a wider range of application scenarioscontainFilter.containThe filter can not only determine if a value exists in a string or array, but also check if a key-value pair (map) or a structure (struct) contains a certain key name. Its result will directly return a boolean value (TrueorFalse),这使得它非常适合与English{% set %}标签结合使用,将判断结果存储起来供后续复杂逻辑使用。
Basic usage:
{{ 集合 | contain:"目标值" }}
1. 判断字符串是否包含某个关键词:
this isinOperator check string similarity, but displayed in the form of a filter.
{# 判断文章内容描述中是否包含“CMS”这个词 #}
{% set description = "欢迎使用安企CMS(AnQiCMS)" %}
{% if description|contain:"CMS" %}
<p>{{ description }} 中包含了“CMS”关键词。</p>
{% endif %}
2. Determine if a certain value exists in an array:
This iscontainOne of the most commonly used scenarios of the filter, especially when the array is obtained after being processed by other filters or tags.
{# 假设我们有一个文章分类ID的列表,并想检查当前文章的CategoryID是否在其中 #}
{% set hotCategoryIds = [1, 5, 8, 12] %}
{% if hotCategoryIds|contain:archive.CategoryId %}
<p>当前文章属于热门分类!</p>
{% endif %}
Please note that for array judgments,containthe filter checks whether the target value iscompletely equalEnglish translation of 'auto' is 'English' in the array element.
3. Check if a key exists in a key-value pair (map) or structure (struct):
This is ainOperators do not directly support, butcontainThe powerful function that can be easily handled by the filter. It allows us to check if an object (such as a configuration object, a set of custom fields) contains a specific attribute or key.
AssumewebInfois an object or map that contains website information, and we want to check if it hasTitleProperties:
{# 假设 webInfo = {Title:"安企CMS", Keyword:"AnQiCMS"} #}
{% set webInfo = system.properties %} {# 比如从系统标签获取的自定义属性 #}
{% if webInfo|contain:"Title" %}
<p>网站信息包含 Title 字段。</p>
{% endif %}
Here,contain:"Title"will checkwebInfoif there exists a key named "Title" in the object or map.
Three, how to choose:inOperator vs.containFilter?
Both methods aim to solve the problem of 'whether a value exists in a set', but in practical applications, they each have their own focus:
Choose
inOperator:- When you need to
{% if %}within a tagDirect, conciseboolean judgment. - The target collection is explicitly a string (check substring) or a simple array/list/map (check elements/keys).
- Pursuing code'sReadability and expressiveness,
target_value in collectionThis natural language writing style is very intuitive.
- When you need to
Choose
containFilter:- When you need to assign a judgment resultto a variableEnglish, so that it can be reused in subsequent complex logic (combined
{% set %}). - when your target set may bemultiple typesOne of (string, array, map, struct) and you want to check them in a unified way.
- when you need to
containJudgment asFilter chainPart of, for example,{{ some_data | another_filter | contain:"value" }}. - When checking is neededmap 或 struct 的键名是否存在时,
containthe filter is a more appropriate choice.
- When you need to assign a judgment resultto a variableEnglish, so that it can be reused in subsequent complex logic (combined
四、实际应用场景举例
No matter which method is chosen, the judgment of whether the value exists in the set is widely used in AnQiCMS templates:
- Navigation menu highlight display:Determine whether the current page URL or ID exists in the sublist of a navigation item, thereby adding 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 that are allowed to access specific content.
- Display features of the article:Based on the article's
FlagProperties (such as "Headlines", "Recommendations") contain specific tags, dynamically displaying different icons or styles. - Dynamic form rendering:Check if the option value of the custom field contains a value already selected by the user to pre-fill the form.
MasteredinOperators andcontainFilter, 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.
Common Questions (FAQ)
Q1: Can I determine if a value does not exist in an array or list?
A1:Of course. You can addinoperator beforenotkeyword, or incontainFilter returns the boolean value before adding!the symbol for inversion.
For example:
- Use
not in:{% if "c" not in archive.Flag %} ... {% endif %} - Use
containFilter inversion:{% 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:Totally valid.inOperators andcontainFilters are all designed to handle dynamic data. As long as your array, list, string, or object is valid and structured correctly during template rendering, both methods will work normally