In the template development of Anqi CMS, we often need to dynamically adjust the page display according to the specific attributes or text fragments of the content.Determine whether a string or array contains a specific keyword is a critical step in implementing this dynamic logic.AnQiCMS Powerful Django style template engine and built-in filters make this operation very intuitive and efficient.

core tools:containFilter

In the AnQiCMS template system, the most direct and recommended tool for determining whether a string or array contains a specific keyword iscontainFilter. This filter returns a boolean value (TrueorFalse) clearly indicating whether the specified keyword exists in the target content.

containThe working principle of the filter

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

  1. For strings (String): containThe filter checks whether the target string contains the specified substring. This is a substring match, and 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 anelement that is completelyequal to the specified keyword.
  3. For key-value pairs (Map) or structures (Struct): containThe filter checks if the object contains akey nameThat matches the specified keyword completely.

How to usecontainFilter?

Its basic syntax is very concise:

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

Usually, we will containFilter is related toifThe logic judgment label is used in combination to execute different template codes based on the judgment results.

Example 1: Check if the article title contains a specific word.

Assuming we want to add a special corner mark or style to documents with titles containing the word "tutorial" in the list of articles.

{% 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.Titleis 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 one.TagsArray (for example:["Go", "CMS", "Web"]),we want to determine whether 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 throughtagListtags to get the tags of the current article, and then collect theTitlefield into a name calledtagTitlesThe array. Finally, usetagTitles|contain:"CMS"to determine if the array contains an element that is exactly equal to “CMS”.

Example 3: Check if a specific key name exists in the key-value pair or structure

If you have a data object (such as fromarchiveParamsRetrieve the custom parameter obtained), and 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"Will check if there is an existing name calledauthorThe key.

Advanced usage:indexandcountFilter

ExceptcontainFilter, AnQiCMS also providesindexandcountFilters, although they do not directly return boolean values, they can also be used indirectly to determine inclusion relationships, and can provide more information in certain specific scenarios.

indexFilter: Get keyword position

indexThe filter returns the first occurrence position (index) of the keyword in the target string or array. If the keyword is not found, it will return-1Therefore, we can determine whether the returned 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: Count keyword occurrences

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 checking whether the returned value is greater than0We can also determine 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 if a string or an array contains a specific keyword, or need to obtain the specific position or occurrence times of the keyword, the built-incontain/indexandcountFilters can provide flexible and powerful support.Reasonably utilizing these tools can help us build more intelligent and dynamic website templates, thereby enhancing user experience and the flexibility of content display.


Common Questions (FAQ)

Q1:containThe filter distinguishes between uppercase and lowercase when judging strings?

A1: Yes,containThe filter distinguishes between uppercase and lowercase when judging strings. For example,"AnQiCMS"|contain:"cms"it will returnFalseBecause 'cms' and 'CMS' do not match completely. If you need to perform a case-insensitive judgment, you may need to convert both the target string and the keyword to a uniform case (e.g., both to lowercase) before usingcontainFilter.

Q2: How to determine if an array element contains a certain substring instead of an exact match of the entire element?any oneelement contains a certain substring, rather than an exact match of the entire element?

A2:containThe filter performs exact matching on elements when processing arrays. If you want to determine if any of the elements (such as strings) in the array contain a substring, you need to combineforloop andcontainFilter to check 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 or element inclusion judgment in sets (arrays, Maps), and it is not suitable for determining if a number is within a certain range. If you need to determine if a number variable is within