How to determine if a string or array contains a specific keyword in a template?

Calendar 👁️ 85

In AnQi CMS template development, we often need to dynamically adjust the page display based on specific attributes or text snippets.Determine whether a string or array contains a specific keyword is a critical step in implementing this dynamic logic.AnQiCMS is a powerful Django style template engine with built-in filters, making this operation very intuitive and efficient.

Core tool:containFilter

The tool that is most directly and recommended in the AnQiCMS template system to determine whether a string or array contains a specific keyword iscontainFilter. This filter can return a boolean value (TrueorFalse), clearly indicating whether the target content contains the specified keyword.

containThe principle of the filter.

containThe filter will use different judgment methods according to the data type you pass to it:

  1. For strings (String): containThe filter checks if the target string contains the specified substring. This is a substring match, as long as any part of the target string matches the keyword, it will returnTrue.
  2. For the array (Array/Slice): containThe filter checks if there is an elementcompletely equal towith a specified keyword.
  3. For a key-value pair (Map) or a structure (Struct): containThe filter checks whether the object contains akey name(key) that matches the specified keyword exactly.

How to usecontainFilter?

Its syntax is very concise:

{{ 目标数据 | contain:"关键词" }}

Generally, we willcontainthe filter meetsifCombine logical judgment tags to execute different template codes according to the judgment results.

Example 1: Determine if the article title contains a specific word

Assume that we want to add a special corner mark or style to the document whose title contains the word 'tutorial' in the article list.

{% archiveList archives with type="list" limit="10" %}
    {% for item in archives %}
    <li>
        <a href="{{item.Link}}">
            <h5>
                {{item.Title}}
                {% if item.Title|contain:"教程" %}
                    <span class="badge tutorial-badge">教程</span>
                {% endif %}
            </h5>
            <p>{{item.Description}}</p>
        </a>
    </li>
    {% endfor %}
{% endarchiveList %}

In this example,item.TitleIt is a string,|contain:"教程"It will check if the article title contains the word "tutorial".

Example 2: Determine if the article tag array contains a specific tag

Assuming each article has oneTagsan array (for example: ["Go", "CMS", "Web"]We want to determine if an article is marked as 'CMS'.

{% archiveDetail archive with name="Id" %} {# 假设这是当前文档的上下文 #}
{% tagList tags with itemId=archive.Id limit="10" %}
    {% set tagTitles = [] %} {# 创建一个空数组用于存放标签标题 #}
    {% for tag in tags %}
        {% set tagTitles = tagTitles|add:tag.Title %} {# 将每个标签的标题添加到数组中 #}
    {% endfor %}

    {% if tagTitles|contain:"CMS" %}
        <p>这篇文章与CMS相关!</p>
    {% else %}
        <p>这篇文章不直接包含“CMS”标签。</p>
    {% endif %}
{% endtagList %}

Here we first go throughtagListLabel to get the current article's tags, then collect theTitlefields into a namedtagTitlesin the array. Finally, usetagTitles|contain:"CMS"to determine whether there is an element in the array that is completely equal to “CMS”.

Example 3: Determine if there is a specific key name in the key-value pair or structure.

If you have a data object (such as one obtained fromarchiveParamscustom parameters you retrieve), you want to check if it contains a certain key.

{% archiveParams params with sorted=false %} {# 获取无序的自定义参数map #}
    {% if params|contain:"author" %}
        <p>本文作者:{{ params.author.Value }}</p>
    {% else %}
        <p>未指定作者信息。</p>
    {% endif %}
{% endarchiveParams %}

Hereparamsis a key-value pair (Map) object,params|contain:"author"it will check if there exists a key namedauthorkey?

Advanced usage:indexandcountFilter

exceptcontainFilter, AnQiCMS also providesindexandcountFilters, although they do not directly return boolean values, can also indirectly determine containment relationships and provide more information in certain specific scenarios.

indexFilter: Get keyword position

indexThe filter will return the position (index) of the first occurrence of the keyword in the target string or array. If the keyword is not found, it will return-1Therefore, we can determine if the return value is greater than or equal to0to determine whether it contains the keyword.

{{ obj | index:"关键词" }}

Example: Determine whether the article content contains a specific word and want to know where it is

{% archiveDetail articleContent with name="Content" %}
    {% set keywordPosition = articleContent|index:"重要信息" %}
    {% if keywordPosition >= 0 %}
        <p>文章内容中包含“重要信息”,首次出现在第 {{ keywordPosition }} 个字符处。</p>
    {% else %}
        <p>文章内容中不包含“重要信息”。</p>
    {% endif %}
{% endarchiveDetail %}

countFilter: Calculate keyword occurrence count

countThe filter will return the number of times the keyword appears in the target string or array. If the keyword does not appear, it will return0. By judging the return value whether it is greater than0, we can also judge whether it contains keywords.

{{ obj | count:"关键词" }}

Example: Calculate the frequency of a word in the article content

{% archiveDetail articleContent with name="Content" %}
    {% set cmsCount = articleContent|count:"CMS" %}
    {% if cmsCount > 0 %}
        <p>“CMS”在文章中出现了 {{ cmsCount }} 次。</p>
    {% else %}
        <p>文章中未提及“CMS”。</p>
    {% endif %}
{% endarchiveDetail %}

Summary

In AnQiCMS template development, whether you need to simply judge whether a string or array contains a specific keyword, or need to get the specific location or occurrence times of the keyword, the built-incontain/indexandcountFilters can provide flexible and powerful support. Reasonable use of these tools can help us build more intelligent and dynamic website templates, thereby enhancing user experience and the flexibility of content display.


Frequently Asked Questions (FAQ)

Q1:containDoes the filter distinguish between uppercase and lowercase when judging strings?

A1: Yes,containThe filter is case-sensitive when judging strings. For example,"AnQiCMS"|contain:"cms"will returnFalseBecause 'cms' and 'CMS' do not match perfectly. If you need to make a case-insensitive judgment, you may need to convert the target string and the keyword to the same case (such as lowercase) first, and then usecontainfilter.

Q2: How to determine if an element in an arrayis any one of themcontains a certain substring instead of an exact match of the entire element?

A2:containThe filter performs an exact match on elements when processing an array. If you want to determine if any element (such as a string) in the array contains a substring, you need to combineforloop andcontainThe filter checks each element one by one.

For example:

{% set tags = ["Go语言", "AnQiCMS系统", "Web开发"] %}
{% set foundPartial = false %}
{% for tag in tags %}
    {% if tag|contain:"CMS" %}
        {% set foundPartial = true %}
        {% break %} {# 找到后即可跳出循环 #}
    {% endif %}
{% endfor %}

{% if foundPartial %}
    <p>数组中有元素包含“CMS”子字符串。</p>
{% else %}
    <p>数组中没有元素包含“CMS”子字符串。</p>
{% endif %}

Q3:containCan the filter be used to determine if a number is within a certain range?

A3:containThe filter is mainly used for substring matching in strings or element inclusion in collections (arrays, Maps), and it is not suitable for determining whether a number is within a certain numerical range. If you need to determine whether a numeric variable is in

Related articles

How to safely escape HTML code in a template to prevent XSS attacks, or force non-escaping of HTML content?

When building a website, ensuring the security of the content, especially the prevention of cross-site scripting (XSS) attacks, is a crucial aspect.AnQiCMS (AnQiCMS) provides powerful tools at the template level to manage the escaping of HTML content, thereby effectively protecting the website and its users.Understanding how to safely handle HTML code in templates is essential knowledge for every AnQi CMS user when performing content operations and template development.### Default security mechanism of AnQi CMS template The template engine of AnQi CMS adopts a design philosophy similar to Django

2025-11-08

How to find the number of occurrences or the first occurrence position of a keyword in a string on a line in a template?

In AnQi CMS template design, sometimes we may need to perform more detailed analysis and display of content, such as finding the position of the first occurrence of a specific keyword in a text, or counting how many times it appears.These requirements are very practical in aspects such as dynamic content display, information extraction, or辅助SEO.Benefiting from the template engine syntax similar to Django adopted by Anqi CMS, we can utilize its powerful filter functions to achieve these goals.Next, we will discuss how to use the built-in `index` and `count` in Anqi CMS template

2025-11-08

How to split a string into an array or concatenate array elements into a single string in a template?

During the development of Anqi CMS templates, we often encounter situations where we need to process strings, such as converting a text segment separated by a specific symbol into a list, or concatenating multiple items in a list into a continuous text.The Anqi CMS template engine provides powerful filters (Filters) to help us easily implement these operations, greatly enhancing the flexibility of the template. ### AnQi CMS Template Engine Basics The AnQi CMS template engine syntax is designed to be very user-friendly, similar to the Django template engine.It is mainly through double curly brackets

2025-11-08

How to display the current year or a custom formatted current date and time in the template?

## In Anqi CMS template, flexibly display the current date and custom time format In website operations, we often need to display date and time information dynamically on the page, whether it is the current year in the copyright statement, the publication time of articles, or the countdown of activities.The AnQi CMS provides a very flexible and easy-to-use method to display the current year or a custom date and time format in templates, keeping your website content up to date and enhancing user experience.The Anqi CMS template system adopts syntax similar to the Django template engine, making the display of dynamic content intuitive

2025-11-08

How does AnQi CMS ensure that articles are automatically displayed on the website front end at the specified time?

In the fast-paced digital content world, how to ensure that content is accurately delivered to the target audience at the right time is a challenge faced by every content operator.Manual operation is not only inefficient but may also lead to release errors due to negligence.The timed release function of AnQiCMS (AnQiCMS) is specifically designed to address this pain point, providing an intelligent and automated way to ensure that your articles are displayed accurately on the website front end at the preset time points.### Understanding the core value of scheduled publishing For content operators, scheduled publishing is not just a convenient tool

2025-11-08

How to display different language versions and content on the front-end of a website through a language switcher based on user selection?

AnQi CMS is an efficient and customizable content management system that excels in multilingual support, allowing operators to easily build multilingual websites for global users.By cleverly utilizing its built-in features, we can build a flexible language switcher on the website front-end, accurately presenting different language versions of content based on user preferences, thereby effectively enhancing user experience and expanding market coverage.### Understanding the Core of Multilingual Support Implementing multilingual support in Anqi CMS is not just a simple text replacement, but a systematic workflow.

2025-11-08

How to ensure that the old link traffic is not lost and the new content is displayed correctly after adjusting the page content structure, by using 301 redirect?

During the operation of a website, content updates, adjustments of the classification structure, or optimization of URL addresses are common operations.However, if not handled properly, these changes are likely to lead to a loss of website traffic and a drop in search engine rankings.幸运的是,AnQiCMS(AnQiCMS)内置了强大的301重定向功能,能够帮助我们平稳地度过这些调整期,确保旧链接的流量能够无缝过渡到新内容。Why 301 Redirects Are Indispensable?301 redirect, i.e., permanent transfer

2025-11-08

How to obtain the Logo image and Banner group image of a specified article or category in Anqi CMS, and apply them flexibly in templates?

## Play with Visual Content: Flexible Calling and Display of Article and Category Logo Images, as well as Banner Group Images in AnQi CMS When building and operating a website, eye-catching visual content is the key to attracting users and conveying the brand image. AnQi CMS understands this and therefore provides a powerful and flexible image management and calling function in the system design, whether it is the cover Logo of the article, the representative thumbnail of the category, or the Banner group images used to create an atmosphere, they can all be easily realized and applied to the website template

2025-11-08