How to check if a specific element exists in an array within a template

Calendar 👁️ 67

In the daily operation and template customization of AnQi CMS, we often encounter situations where we need to dynamically adjust the page display based on the data content.One common and practical requirement is to determine whether a specific element exists within an array (or list) in a template.This is crucial for implementing personalized recommendations, conditional content display, and even for functions such as permission control.

The AnQi CMS uses a template engine syntax similar to Django, providing rich tags and filters to handle data.When we receive some data collections from the backend, such as a list of article tags, a group of product images, or multiple values of a custom field, these data are often presented in the form of an array.At this point, if we need to decide what content to display based on whether an array contains a certain value, we can cleverly use built-in filters to achieve this.

Core Tips: UsecontainFilter

In the AnQi CMS template system, the most direct and recommended method for checking if a specific element exists in an array is to usecontainA filter that is powerful and easy to understand, it determines whether a string, array (slice), key-value pair (map), or struct contains the specified keyword or key name and returns a boolean value (TrueorFalse)

Let's look at a simple example. Suppose you have a custom article feature, the article can be associated with multiple features, and these features are stored in an array.article.FeaturesFor example,["多图", "置顶", "推荐"]Judging whether the current article contains the 'recommended' feature in the template to display a special marker.

{# 假设 article 是当前文章对象,其 Features 是一个字符串数组 #}
{% set articleFeatures = '["多图", "置顶", "推荐"]'|list %}

{% if articleFeatures|contain:"推荐" %}
    <span class="badge badge-primary">编辑推荐</span>
{% else %}
    <span>普通文章</span>
{% endif %}

In this code, we first usesetandlistThe filter simulates an array of features.articleFeatures. Then,{% if articleFeatures|contain:"推荐" %}This line of code is the core judgment: it callscontainthe filter to checkarticleFeatureswhether the array contains the string “recommend”. If it contains, the condition isTrueWill display the 'Editor's Recommendation' badge; otherwise, the condition isFalseDisplay 'Normal Article'.

Another option:indexFilter

exceptcontainFilter, you can also consider usingindexFilter to achieve a similar purpose.indexThe filter returns the first occurrence position (index) of the specified keyword in a string or array, if not found, it returns-1. Therefore, by checking if the returned value is not equal to-1We can also confirm the existence of the element.

{% set articleFeatures = '["多图", "置顶", "推荐"]'|list %}

{% if articleFeatures|index:"置顶" != -1 %}
    <span class="badge badge-warning">置顶文章,位于第 {{ articleFeatures|index:"置顶"|add:1 }} 位</span>
{% else %}
    <span>未置顶</span>
{% endif %}

In this example,articleFeatures|index:"置顶"It will return the index of "top" in the array (here is1Because the array index starts from0). We go through!= -1Check if it exists. If it does, we can also make additional use ofindexThe specific position information returned by the filter, through|add:1Converted to a sequence number starting from 1 that is more in line with human habits.

AlthoughindexThe filter can also implement existence judgment, but if you just want to know if an element exists,containThe filter is semantically clearer and the code is also more concise.indexMore suitable for the scenario where you need to obtain the specific location after confirming the element exists.

Example of practical application scenarios

Let's combine the commonly used tags of AnQi CMS and see how these filters are applied in actual templates:

  1. Display icons according to the recommended attributes of the article:AnQi CMS article details (archiveDetailThere usually isFlagA field is used to mark the recommended attributes of an article, such ashrepresenting the headline,cThis represents a recommendationFlagIt may be a string containing multiple letters, such as"hc". We can usecontainFilter it to check it.

    {% archiveDetail currentArticle %}
    <h1 class="article-title">{{ currentArticle.Title }}</h1>
    {% if currentArticle.Flag|contain:"h" %}
        <img src="/static/images/hot.png" alt="头条文章" title="头条文章" class="flag-icon">
    {% endif %}
    {% if currentArticle.Flag|contain:"c" %}
        <img src="/static/images/recommend.png" alt="推荐文章" title="推荐文章" class="flag-icon">
    {% endif %}
    <div class="article-content">{{ currentArticle.Content|safe }}</div>
    
  2. Special processing for the product detail page image group:Assuming your product model has aImagesfield, stores the URL array of product galleries. You may want to check if it contains a specific promotional image for special display on the page.“`twig {% archiveDetail productDetail with name=“Images

Related articles

How to judge whether a line of text in the AnQiCMS template contains a certain keyword?

In website operation, we often encounter such needs: to decide how to display page elements based on whether the content contains a specific word, such as highlighting some text, or only displaying a module when certain conditions are met.The AnQiCMS template system provides flexible filter functions to help us easily implement these keyword-based judgments.This article will delve into how to efficiently and accurately determine whether a line of text in the AnQiCMS template contains a certain keyword.### Use `contain`

2025-11-08

What are the practices when using the `count` filter to calculate keyword density?

In website content operation, the reasonable use of keywords is an important factor in improving search engine visibility.We not only need to ensure that the core keywords are reflected in the content, but also need to pay attention to their frequency of occurrence, avoiding overloading or underusing.AnQiCMS provides a variety of powerful content management tools, among which the `count` filter is a very practical feature that can help us effectively count the number of occurrences of keywords in articles.###

2025-11-08

How to calculate the total number of occurrences of a specific value in an array in AnQiCMS?

In website operation, we often need to handle various data, one of the common needs is to count the number of times a specific value appears in a data set.For example, you may want to know how many times a keyword appears in an article, or how many colors of a product are marked as 'hot'.For users of AnQiCMS, the system's powerful template engine provides a very convenient tool to complete this task.The AnQi CMS template engine is powerful and flexible, it comes with a variety of filters (Filters)

2025-11-08

How to count the frequency of a keyword in a string in the AnQiCMS template?

In content operation, we often need to process and analyze text.This may involve checking keyword density to optimize search engine rankings, or it may just be to understand the frequency of a specific word appearing in the content in order to better assess the focus of the content.AnQiCMS (AnQiCMS) boasts its high efficiency and customizable features, providing users with powerful content management capabilities, and its flexible template system makes it easy for us to handle various content display needs.Today, let's talk about a very practical feature: how to count the number of times a keyword appears in a string in a template

2025-11-08

What role can the `contain` filter play in the context of sensitive word filtering?

In today's era where content is king, website operators are facing the dual challenge of actively publishing high-quality content while strictly controlling content security and compliance.Especially on platforms where user-generated content is increasing, how to efficiently and accurately filter sensitive words has become a key link in maintaining a healthy website ecosystem and protecting brand reputation.AnQiCMS (AnQiCMS) fully understands this need and provides many content security management functions, among which the `contain` filter can play a surprisingly practical role in the sensitive word filtering scenario.### The Foundation of Content Security

2025-11-08

How to get the first occurrence position of a keyword in a string in AnQiCMS

In content operation, we often need to fine-tune and manage the text content on the website.In order to content review, dynamic display, or SEO optimization, sometimes we need to know the position of the first occurrence of a specific keyword in a text.AnQiCMS (AnQiCMS) is an efficient content management system that provides a convenient way to help us meet this need.Understanding the need: Why do we need to find the position of keywords?Understanding the position of keywords in strings is of great practical value in the process of content publishing and maintenance

2025-11-08

What is the speciality of the `index` filter for Chinese position calculation when processing multi-language content?

## A clever approach: The unique features of `index` filter and Chinese position calculation in AnQi CMS multilingual content When managing multilingual content with AnQi CMS, the flexible use of its powerful template engine and rich filters can greatly improve content operation efficiency.Among them, the `index` filter is a very practical tool that helps us quickly locate the first occurrence of a specific substring in a string.However, when our content involves Chinese characters, the `index` filter has some unique behavior in position calculation.

2025-11-08

How to count the character length of article titles, descriptions, or custom fields?

When managing content on AnQi CMS, we often need to pay attention to the character length of article titles, descriptions, or custom fields.This concerns not only SEO optimization, ensuring that the title and description are in line with the practices of search engines, but also affects the reading experience of users on the search results page or within the website's internal list.How can you easily count the character length of this content in Anqi CMS templates?The Anqi CMS built-in template engine provides many practical filters (filters), among which the `length` filter is our tool for counting character length

2025-11-08