How to judge whether a string or array contains a specific keyword and display the result in AnQiCMS template?

Calendar 👁️ 71

When building and managing website content, we often encounter the need to determine whether to display a "hot" tag based on whether the article title contains a certain keyword;Or check if the product description mentions a certain feature, thereby adjusting its display style.These subtle dynamic adjustments can greatly enhance the intelligence and user experience of the website.In AnQiCMS, due to its flexible Django template engine syntax, implementing such judgments is not complicated.

The AnQiCMS template system provides rich filters and logic tags, allowing content operators to implement complex logical judgments at the front-end template level without delving into the backend code.Today, let's talk about how to judge whether a string or array contains a specific keyword in the AnQiCMS template and display content intelligently according to the result.

Core tool:containFilter

AnQiCMS's template engine provides a very practicalcontainA filter that can help us quickly determine whether a string contains a specific word or whether an array contains a specific element.It works very intuitively, and it will returnTrueorFalseboolean value for convenient subsequent logical judgment.

For example, if you want to check if a text contains the word 'CMS', you can write it directly like this:

{{ "欢迎使用安企CMS(AnQiCMS)"|contain:"CMS" }}

The code will output directly after executionTrue.

If your data is an array, such as a list of article tags, and you want to know if it contains the tag "SEO optimization", you can first convert the comma-separated string to an array, then usecontaina filter to make the judgment:

{% set tags_string = "安企CMS,SEO优化,多站点管理" %}
{% set tags_array = tags_string|split:"," %} {# 使用 split 过滤器将字符串按逗号分隔成数组 #}
{{ tags_array|contain:"SEO优化" }}

This will also outputTrue.

Even,containThe filter can also be used to check if a key-value pair (map) or a structure (struct) contains a certain key name (key). For example, if you have an object storing product information, you want to know if it contains the key "version":

{% set product_info = {name: "AnQiCMS", version: "3.0"} %}
{{ product_info|contain:"version" }}

This will also outputTrue.

CombineifLabel, intelligent display content

It is obviously not enough to know True or False, we need to take action based on this result. At this point, the template inifLogical judgment tags come into play. We can usecontainthe result of the filter directly inifthe statement to achieve conditional display of content.

Imagine that you want to add a prominent "New Arrival" label to all articles whose titles contain "New Product". In the article list template, you can do it like this:

{% archiveList articles with type="list" limit="5" %}
    {% for item in articles %}
        <li>
            {% if item.Title|contain:"新品" %}
                <span style="color: red; font-weight: bold;">【新品上市】</span>
            {% endif %}
            <a href="{{item.Link}}">{{item.Title}}</a>
            <p>{{item.Description|truncatechars:100}}</p>
        </li>
    {% empty %}
        <p>暂时没有文章。</p>
    {% endfor %}
{% endarchiveList %}

This, only when the article titleitem.Titlecontains 'New Product', the red '【New Product Launch】' text will be displayed.

If your judgment conditions are more complex, you need to check multiple keywords at the same time, or satisfy any one of them is enough,iflabel'sandandorLogical operators come into play. For example, when a description of an article mentions both "Go language" and "SEO optimization", a specific prompt is displayed:

{% set article_desc = "安企CMS是基于Go语言开发的系统,支持多站点和强大的SEO优化功能。" %}
{% if article_desc|contain:"Go语言" and article_desc|contain:"SEO优化" %}
    <p>这篇文章深度探讨了Go语言和SEO优化。</p>
{% elif article_desc|contain:"多站点" %}
    <p>这篇文章介绍了多站点管理特性。</p>
{% else %}
    <p>文章内容普通。</p>
{% endif %}

More practical filters to assist in judgment and display

exceptcontainIn addition, the AnQiCMS template also provides some filters related to keyword judgment and display, which can provide help in different scenarios.

  • countFilter: Calculate keyword occurrence countSometimes, we not only want to know if a certain keyword is 'present' or 'absent', but also how many times it appears.countThe filter can help you achieve this.

    {% set article_content = "安企CMS,高效的CMS,值得信赖的CMS,让你的CMS运营更轻松。" %}
    <p>"CMS" 在文章中出现了 {{ article_content|count:"CMS" }} 次。</p>
    

    This will output"CMS" 在文章中出现了 3 次。

  • indexFilter: Get the position of the first occurrence of the keywordIf the position of the keyword is important for your content display,indexThe filter can return the starting position of the first occurrence of a keyword. If not found, it returns-1.

    {% set intro_text = "AnQiCMS是领先的CMS内容管理系统。" %}
    {% set cms_position = intro_text|index:"CMS" %}
    {% if cms_position != -1 %}
        <p>"CMS" 首次出现在文本的第 {{ cms_position }} 个位置。</p>
    {% else %}
        <p>未找到"CMS"。</p>
    {% endif %}
    

    Please note that Chinese characters occupy multiple bytes when calculating positions, which may result in differences from expectations; it is usually more accurate in English situations.

  • splitFilter: Split a string into an array.As shown in the previous array example, when your data source is itself a comma-separated, space-separated, or other symbol-separated string, but you need to treat it as an array when evaluating it,splitThe filter can help you. It can split a string into an array of strings according to a specified delimiter.

    `twig {% set product_features_str = "high performance,module design,SEO friendly" %} {% set product_features_array = product

Related articles

How to use AnQiCMS filter to display strings centered or aligned to a specified length?

In website content display, we often need to format text to make it more beautiful and tidy in layout, especially in lists, tables, or areas that require a unified visual effect.AnQiCMS (AnQiCMS) powerful template engine provides a variety of practical filters (filters) that can help us easily achieve centered, left-aligned, or right-aligned strings and can be filled to a specified length.

2025-11-07

How to perform addition of numbers and strings in AnQiCMS template and display the result?

When building dynamic content in AnQi CMS templates, it is often necessary to perform simple calculations and concatenations of numbers or strings.Whether it is to display the cumulative user points or to combine and display product codes with specific prefixes, Anqi CMS provides a flexible and convenient way to meet these needs.This article will deeply explore how to perform addition operations in the AnQiCMS template, and provide detailed examples and practical suggestions.### Understanding the computational capabilities of AnQi CMS template The AnQi CMS template system is based on syntax similar to the Django template engine

2025-11-07

How to display the AnQiCMS page's canonical URL?

In website operation, we often encounter the situation where content appears repeatedly under different URLs.For example, a product may have multiple colors, each color generating an independent page, but their core content is the same.Or, in order to track traffic, websites may add various parameters to the URL.This "duplicate" content, although it has little impact on user experience, but it may confuse search engines, not knowing which is the "original version", thus possibly affecting the crawling efficiency and ranking of the website.

2025-11-07

How to correctly configure the pseudo-static rules in AnQiCMS to generate URLs that are friendly to users and search engines?

In website operation, a URL structure that is friendly to both users and search engines is crucial.It not only allows visitors to understand the page content at a glance, but also makes it convenient for search engines to crawl and understand your website, which directly affects the SEO performance and user experience of your website.AnQiCMS (AnQiCMS) knows this well, therefore it is built with powerful pseudo-static features, allowing you to easily customize the URL of your website.Next, we will explore how to correctly configure the pseudo-static rules in AnQiCMS to generate those beautiful and practical URLs.

2025-11-07

How to calculate the number of occurrences of a specific keyword in the AnQiCMS template string or array?

In daily website operations, we often need to analyze and manage content in detail.One common requirement is to count the number of occurrences of a specific keyword in a string or array within a website template.It is very helpful to understand how to implement this feature in AnQiCMS templates, whether it is for optimizing SEO keyword density, analyzing content hotspots, or for dynamically displaying relevant information on the page.AnQiCMS benefits from its powerful and flexible Django-style template engine, providing rich built-in tags and filters, making these operations extremely simple.

2025-11-07

How to remove the specified characters from a string in the AnQiCMS template to optimize display?

In website operation, the clarity of content presentation and user experience are crucial.Sometimes, the content we enter from the background or the fields we retrieve from the database may contain some unnecessary characters, such as extra spaces, specific delimiters, or leading text that needs to be cleaned up, all of which may affect the aesthetics of the page and the readability of the content.

2025-11-07

How to convert a numeric string in AnQiCMS template to a floating-point number or integer for display?

In AnQiCMS template development, data processing is one of the core links.The flexible content model allows us to customize various fields to store website information, including scenarios where numbers are needed, such as product prices, inventory quantities, ratings, and so on.Although these numbers may look normal in the background, they are likely to be presented as strings when called in the template.This brings up a common question: How can we convert these numeric strings to floating-point numbers or integers in a template for mathematical operations or specific formatting?

2025-11-07

How to link array elements into a string for display in AnQiCMS template?

In AnQiCMS template development, we often encounter situations where we need to display a series of related data, such as multiple tags of an article, various characteristics of a product, or multiple options stored in a custom field.These data are often present in the template in the form of an array, and we hope to display them in a concise and beautiful string format, such as connecting them with commas, slashes, or other symbols.

2025-11-07