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