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

Calendar 👁️ 60

Secure CMS Template: Exploring the checking of key-value pairs and member existence in structures

As an experienced website operations expert, I know how important it is to operate data flexibly and effectively 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: how to check if a key (key) exists in a map (key-value pair) or a struct (struct).

In AnQiCMS template engine, we have a variety of methods to achieve this goal, each with its own focus, meeting the needs of different scenarios.We will detail the two aspects of the built-in operators and powerful filters of the template engine.

In the template, the “in” operator: intuitive member detection

First, the Anqi CMS template engine provides a very intuitive and easy-to-understandinAn operator that allows us to check if an element belongs to a set in a conditional statement.This "collection" can be a list (such as a slice or array in Go language), or a key-value pair (map) or a struct.

When used with lists or arrays,inThe operator checks if a list contains a certain value. For example, if you have a list containing multiple strings and want to know if it contains "SEO optimization", you can write it like this:

{% if "SEO优化" in 网站优势列表 %}
    <p>我们的安企CMS在SEO优化方面表现出色!</p>
{% endif %}

And when we face ismap(key-value pair) orstruct(struct) wheninThe operator can checkkey nameDoes the (key) exist. This is very useful for dynamically displaying content, or determining whether to display a module based on the existence of the data structure.

For example, in the AnQi CMS template design, we often encounterarchive(document) object, which may contain various fields. Suppose we want to know somearchiveWhether the object contains a namedViewsThe field (usually representing page views), we can judge it like this:

{% if "Views" in archive %}
    <p>浏览量:{{ archive.Views }}</p>
{% else %}
    <p>此文档暂无浏览量数据。</p>
{% endif %}

For example, you might have one passed from the backgroundintmap(integer key-value pair), want to check the number5Does it exist as a key:

{% if 5 in simple.intmap %}
    <p>键5存在于intmap中。</p>
{% endif %}

This method is concise and clear, especially suitable forifdirect conditional judgment in statements.

A more elegant choice:containFilter

exceptinOperator, Anqi CMS also provides a more powerful and flexible feature.containFilter, it can be combined with other operators in the form of a filter chain to achieve more complex data processing.containThe filter can not only judge whether a substring is contained in a string, but also efficiently check whether a value exists in an array, andDoes the key exist in the key-value pair (map) or structure (struct)?.

containThe filter returns a boolean value when used,TrueorFalseThis makes it very suitable for storing check results in variables, for subsequent multiple logic branches.

Let's understand through a specific example.containThe application of filters in checking map or struct key names:

Suppose you have a variable namedwebInfoThe key-value pair contains the website's title (Title), keywords (Keyword) and description (Description). Do you want to checkTitleDoes this key exist:

{% set webInfo = {'Title': '安企CMS', 'Keyword': 'AnQiCMS', 'Description': '免费建站系统'} %}

{% if webInfo|contain:"Title" %}
    <p>网站信息中包含Title键:{{ webInfo.Title }}</p>
{% else %}
    <p>网站信息中不包含Title键。</p>
{% endif %}

The advantage of this writing style is,containThe boolean value returned by the filter can be directly{% set %}Labeled and assigned to a new variable, improving the readability and reusability of the code:

{% set webInfo = {'Title': '安企CMS', 'Keyword': 'AnQiCMS', 'Description': '免费建站系统'} %}
{% set hasTitleKey = webInfo|contain:"Title" %}

{% if hasTitleKey %}
    <p>我们确定网站信息中包含Title键!</p>
{% else %}
    <p>Title键缺失,请检查网站配置。</p>
{% endif %}

containThe filter is also powerful when handling strings and arrays. For example, check if a piece of text contains a certain word:

{% set welcomeText = "欢迎使用安企CMS(AnQiCMS)" %}
{% if welcomeText|contain:"CMS" %}
    <p>欢迎语中提到了CMS。</p>
{% endif %}

Or check if an element exists in a list (slice):

{% set features = ["多站点管理", "灵活内容模型", "SEO工具"] %}
{% if features|contain:"SEO工具" %}
    <p>安企CMS确实提供了强大的SEO工具。</p>
{% endif %}

When to use which? Scenario analysis

Then, ininOperator andcontainBetween filters, how should we choose?

  1. For simple conditional judgmentsIf you just need to{% if ... %}quickly check if a key exists in a statement without storing the result or performing other chained operations, theninOperators are usually a more concise and intuitive choice.

    {% if "author" in archive %} ... {% endif %}
    
  2. For cases where the result needs to be assigned to a variable or for complex filtering chains: If you wish to store the check results in a variable, or need to perform other data filtering and processing before/after the check, thencontainThe filter has more advantages. Filters usually provide greater flexibility.

    {% set hasCustomField = archive.Extra|contain:"custom_field_name" %}
    {% if hasCustomField %} ... {% endif %}
    
  3. For unified syntax checking: If you want to check the existence of members in strings, arrays, or key-value pairs using a unified filter syntax, thencontainThe filter would be a better choice, as it provides a consistent interface.

This design of the Anqi CMS template engine provides strong flexibility for website operators and developers, allowing us to choose the most suitable tool to efficiently process data based on specific data types and business logic.


Frequently Asked Questions (FAQ)

  1. Can I usenot inor!Are you using the operator to check if a key does not exist?Of course, you can. In AnQi CMS template engine, you can usenot into express the logical 'not included' directly, or ininAdd the result of the operator before!To implement (logical NOT). For example,{% if "author" not in archive %}or{% if not ("author" in archive) %}Can be checkedauthorKey exists. Similarly,containThe filter returns a boolean value, you can directly negate it:{% if not (webInfo|contain:"Title") %}.

  2. How can I find not only if the key exists but also get the position of its value in an array or string?If you need to get the first occurrence position of a value in a string or array, you can use the Anqi CMS providedindexfilter. It will return the value from0The starting index position, if not found then return-1. Please note,indexThe filter is mainly used for locating values of strings and arrays, not for locating keys of key-value pairs. For example:{{ "欢迎使用安企CMS"|index:"CMS" }}.

  3. fields of a custom content model can also be usedinor operatorcontainfilter check?Yes, the fields of the custom content model in AnQi CMS are usually present as attributes of document or category objects (structs in Go language). Therefore, you can check them as you would check any struct field.inOperator (for example{% if "customFieldName" in archive %}orcontainfor example, a filter (such as{% if archive|contain:"customFieldName" %}) to determine whether these custom fields exist. This provides great convenience for dynamically displaying content based on the presence or absence of custom fields.

Related articles

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

As an experienced website operation 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 determine if a value exists in an array or list in AnQiCMS templates (i.e., the functionality of the `in` operator)?In the display of dynamic content

2025-11-06

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 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

How to convert a string number to an integer for calculation in AnQi CMS template (integer)

## Taming Data: The Mystery of Converting String Numbers to Integers in AnQi CMS Templates (Deta...AnQiCMS (AnQiCMS) boasts a high-performance architecture based on the Go language and a flexible Django-style template engine, providing powerful tools for content operators.However, data is often stored in databases or entered by users in string format.

2025-11-06