How to determine whether an array or string in an Anqicms template contains a specific keyword?

Calendar 👁️ 61

In Anqi CMS template development, we often need to dynamically display information based on specific attributes or keywords of the content.For example, determine whether an article title contains a product name or check if a document's tag list contains a popular keyword.This not only makes the website content more targeted, but also improves user experience and SEO effectiveness.

The AnQi CMS template engine provides powerful and flexible features to meet these needs. Among them, determining whether an array or string contains a specific keyword can be achieved by cleverly using built-incontainImplement filters easily.

UnderstandingcontainFilter

containThe filter is a very practical tool in the Anq CMS template, which helps us determine whether a value (string, array, slice in Go language, map or struct) contains another specified value (i.e., the keyword). After execution, this filter returns a boolean value: if it contains, it returnsTrue; if it does not contain, it will returnFalse.

Its basic usage is very intuitive:

{{ obj|contain:关键词 }}

Here, objrepresent the string or array variable you want to check, and关键词is the target you want to find.

Actual application scenario: Determine the keywords in the string

Assuming you want to check the title of an Anqi CMS article (archive.Title) to see if it contains the brand name 'Anqi CMS'. You can use it in the template like thiscontainFilter:

{% set articleTitle = archive.Title %} {# 获取当前文章的标题 #}

{% if articleTitle|contain:"安企CMS" %}
    <p>当前文章标题“{{ articleTitle }}”中包含了“安企CMS”这个词!</p>
{% else %}
    <p>当前文章标题“{{ articleTitle }}”中未包含“安企CMS”。</p>
{% endif %}

In this way, you can add special tags or styles to articles in the list that contain specific brand keywords to attract the attention of users. Similarly, if you want to check the content of the articles (archive.Content) Is there a specific phrase, you can also use the same method. However, please notearchive.ContentIt usually contains HTML, if you need to search for plain text, you may need to remove the HTML tags first (for example usingstriptagsfilter), and then perform keyword judgment.

The actual application scenario: to judge the keywords in the array

In AnQi CMS, many data exist in the form of arrays (or slices in Go language), such as the tag list of articles (tagsIf you want to determine whether an article has been tagged with "marketing", you can do it like this:

First, wetagListTagging to get the tag list of the article and assign it to a variable. Then, usecontainFilter to check if the list contains the target tag.

{% tagList currentArticleTags with itemId=archive.Id %} {# 获取当前文章的所有标签,赋值给currentArticleTags #}

{% if currentArticleTags|contain:"营销" %} {# 检查标签列表中是否包含“营销”这个字符串 #}
    <p>这篇文章被标记为“营销”类别。</p>
{% else %}
    <p>这篇文章没有“营销”标签。</p>
{% endif %}

It is worth noting that whencontainThe filter is used on an array, it checks if each element in the array matches the keyword you provide.

Advanced usage: Handling non-standard array data.

Sometimes, the custom fields you define may store a string connected by commas or other delimiters, and you want to treat it as an 'array' for keyword judgment. For example, you define a field namedrelatedKeywordsThe custom field stores the format as "keyword1, keyword2, keyword3".

In this case, you can first usesplitThe filter splits this string into a real array and then uses itcontaina filter to make the judgment:

{% set relatedKeywordString = archive.relatedKeywords %} {# 假设这是一个自定义字段 #}
{% set relatedKeywordArray = relatedKeywordString|split:", " %} {# 将字符串按", "拆分成数组 #}

{% if relatedKeywordArray|contain:"SEO" %}
    <p>这篇文档与SEO主题高度相关。</p>
{% else %}
    <p>这篇文档没有明确的SEO相关关键词。</p>
{% endif %}

here,split:", "Split strings with a comma and space as the delimiter. You can adjust according to the delimiter you are actually using.splitThe parameters after the filter.

Summary

containThe filter is a simple yet powerful tool in Anqi CMS template, which makes it very convenient to perform keyword judgment on string and array data at the template level.Whether it is for conditional judgment, dynamic content display, or filtering based on user input, mastering this filter can make your website content operation more flexible and efficient.Through combiningifLogical labels andsplitAn auxiliary filter, you can build more intelligent and interactive website features to better meet the needs of visitors.


Frequently Asked Questions (FAQ)

  1. Q: Can I also count how many times a keyword appears in a string, in addition to checking if it contains it?A: Of course. Anqi CMS template providescountA filter to meet this requirement. You can use{{ obj|count:关键词 }}to get the number of times a keyword appears in a string or array. For example,{{"安企CMS安企CMS"|count:"CMS"}}it will return2.

  2. Q: I just want to know the specific position of the keyword in the string, not just to judge if it exists. Is there a way to do that?A: Yes. You can useindexA filter to find the first occurrence of a keyword. It returns an integer representing the starting index of the keyword in the string (counting from 0).If the keyword is not found, it will return-1For example,{{"欢迎使用安企CMS"|index:"CMS"}}May return18The length of the string depends on the actual UTF-8 encoding.

  3. Q: If the array I need to judge contains objects (such as a list of articles),containCan the filter directly judge the value of an object's attribute?A:containWhen the filter is used for an array containing objects, it will try to match each object in the array with the keyword you providePerfect matchIf your keyword is a string, it will only check if there is an object exactly the same as the string in the array.To determine the properties of an object (for example, to determine whether there is an article with a Title of "some title" in a list of article objects), you need to traverse the array and use it in the loop.ifCheck each object's specific attribute individually. For example:{% for item in articles %}{% if item.Title|contain:"某个标题" %}{# 逻辑 #}{% endif %}{% endfor %}.

Related articles

How does the `slice` filter implement the function of extracting elements from the end of an array?

In AnQiCMS template development, the `slice` filter is a very practical tool that allows us to flexibly extract a part of the string or array content.But do you know? It can also realize a particularly clever function - to extract elements from the end of an array or list, which is very convenient when it comes to displaying the latest data or removing old data.Today, let's delve into how the `slice` filter achieves this functionality through negative indices.Understanding the basic usage of the `slice` filter As the name implies

2025-11-08

How to extract elements within a specified range from an array or string in Anqi CMS template?

In AnQiCMS template development, we often need to finely control the displayed content, such as extracting part of the information from a long text, or displaying only the first few elements from a list.Fortunately, AnQiCMS uses a Django-like template engine that provides a very useful tool - the `slice` (slicing) filter, which can help us easily meet these needs.The `slice` filter is a very flexible feature that is not only applicable to string (text) but also to array (list) data

2025-11-08

How does the `join` filter behave when processing non-array objects (such as strings)?

In Anqi CMS template development, the `join` filter is a very practical tool, mainly used to concatenate elements of an iterable object (such as an array or list) into a single string with a specified separator.However, when we apply the `join` filter to non-array objects, especially strings, its behavior may be different from what we initially imagine, but understanding its working principle can help us use it more flexibly.### The basic functionality of `join` filter review First, let's review the most common uses of the `join` filter

2025-11-08

How to concatenate array elements in an Anqi CMS template with a custom character into a string?

In AnQi CMS template design, we often encounter situations where we need to display list-type data, such as multiple tags of an article, multiple image links on a product details page, or multiple options stored in a custom field.Directly outputting these array-shaped data to the page will often show a similar format like `["Label one", "Label two", "Label three"]`, which clearly does not meet the aesthetic and reading habits of users.At this point, we need to find a method to separate each element of the array with a custom character (such as a comma

2025-11-08

Can the `contain` filter be used to check if a Map (key-value pair) contains a specific key?

AnQiCMS with its efficient and customizable features brings many conveniences to content management.In the daily operation of websites, we often need to dynamically adjust the page content in templates based on the existence of data.Among them, it is a common requirement to judge whether a specific key exists in the data of key-value pair (Map) type.Today, let's delve into whether and how the `contain` filter in AnQiCMS templates can be used to check for the existence of keys in a Map.

2025-11-08

How to calculate the number of times a keyword appears in a string or array in the Anqi CMS template?

In content operation, precisely mastering the use of keywords on the page plays a crucial role in SEO strategy, content quality assessment, and user experience optimization.AnQiCMS (AnQiCMS) is a flexible and efficient content management system with a powerful template engine built-in with many practical features, including a filter that can help us easily calculate the number of times keywords appear.Next, we will introduce how to use these features to count the frequency of keywords in the Anqi CMS template.### Deeply understand `count`

2025-11-08

The `count` filter calculates the number of times a keyword appears in an array, is it a partial match or a complete match?

In Anqi CMS template development, the `count` filter is undoubtedly a very practical tool for processing data, which can help us quickly count the frequency of a specific keyword in the data.However, when using this filter, many users may be puzzled: when it handles string and array data of different types, is the keyword matching method 'partial matching' or 'exact matching'?This is crucial for accurately presenting content data.

2025-11-08

How to randomly select an element or character from an array or string in Anqi CMS template?

In Anqi CMS template, adding dynamism and fun to the content is an important aspect of improving user experience.Sometimes, we hope to display a random element on the page, such as a random slogan, a random recommendation tag, or randomly select a picture from a group of images.AnQi CMS relies on its flexible Django template engine syntax to provide a simple yet powerful way to meet this requirement, with the core tool being the `random` filter.

2025-11-08