How to determine if a string contains a substring in AnQiCMS template?

Calendar 👁️ 72

In the daily operation and template design of AnQiCMS, we often need to determine how to display it based on the specific attributes of the content.For example, you may want to highlight articles with a specific keyword in the title, or adjust the style based on whether there is a specific word in the product description.How to determine whether a string contains another substring in a template has become a very practical skill.

The AnQiCMS template system is based on the Django template engine syntax, providing rich tags and filters to help us flexibly handle data.We can cleverly utilize several built-in filters for string inclusion judgments.

Core method one: utilizingcontainDirect judgment by filter

The most direct and recommended method is to usecontainA filter. This filter is specifically used to determine whether a string, array, or map (map/struct) contains a certain substring or key.Its return value is a boolean value (TrueorFalse),It is very suitable for use in conditional judgments.

Its basic usage is very simple, you just need to take the string to be checked asobj, and the substring to be searched as parameters:

{{ obj|contain:"子串" }}

For example, let's assume we have an article titlearchive.TitleTo determine if it contains the word 'CMS':

{% if archive.Title|contain:"CMS" %}
    <span style="color: red;">文章标题中包含“CMS”!</span>
{% else %}
    <span>文章标题中不包含“CMS”。</span>
{% endif %}

In the above example, ifarchive.TitleThe value is 'Welcome to AnQiCMS (AnQiCMS)', then the page will display 'The article title contains 'CMS'!'.

containThe strength of the filter also lies in its versatility. It can not only check ordinary strings, but also search in arrays (slice) and key-value pairs (map/struct).

For example, if you have an array of article tagstagsto check if it contains a specific tag:

{% set tags = "Go语言,内容管理,SEO优化"|split:"," %} {# 假设tags是一个字符串,我们先用split过滤器转换为数组 #}
{% if tags|contain:"SEO优化" %}
    <p>这篇文章与SEO优化相关。</p>
{% endif %}

Or, if you have a mapping that contains additional configuration informationconfigWould you like to check if a key exists:

{% set extraConfig = { author:"AnQiCMS团队", release_date:"2023-01-01" } %}
{% if extraConfig|contain:"author" %}
    <p>作者信息已配置:{{ extraConfig.author }}</p>
{% endif %}

Core method two: utilizingindexFilter assists in judgment

exceptcontain,indexFilter is also a very useful tool.indexThe filter returns the position of the first occurrence of the substring in the target string (starting from 0). If the substring does not exist, it returns-1We can use this feature to indirectly determine if a substring exists.

Its basic usage is as follows:

{{ obj|index:"子串" }}

For example, we still use the article title.archive.Title:

{% if archive.Title|index:"CMS" != -1 %}
    <span style="font-weight: bold;">发现“CMS”字样,位置在 {{ archive.Title|index:"CMS" }}!</span>
{% else %}
    <span>未发现“CMS”字样。</span>
{% endif %}

AlthoughindexCan also implement the same judgment logic, but usually, if it is just to judge whether it exists,containThe filter will be more concise and intuitive, and also more in line with semantics. If you need to get the specific position of a substring, thenindexThe filter is your best choice.

Practical skills and precautions

  1. Make good use of{% set %}Tags:When you make complex judgments or need to refer to judgment results multiple times, you can store the filter results in a variable, which can improve the readability and maintainability of the template:

    {% set hasSpecialKeyword = archive.Title|contain:"重要" %}
    {% if hasSpecialKeyword %}
        <span class="highlight-label">重要文章</span>
    {% endif %}
    
  2. Case sensitivity:By default,containandindexFilters are allCase sensitiveThis means that "CMS" and "cms" are considered different substrings.If you need to make a case-insensitive judgment, you can consider converting the string to a uniform case before comparison, for example:

    {% if archive.Title|lower|contain:"cms" %} {# 将标题全部转为小写后再判断 #}
        <span class="info">标题中不区分大小写包含“cms”</span>
    {% endif %}
    
  3. Support for Chinese:The filter of AnQiCMS supports Chinese well, no mattercontainOrindex, it can correctly handle Chinese string.

With these simple and powerful filters, you can flexibly judge whether a string contains a specific substring in the AnQiCMS template, thus realizing more dynamic and intelligent content display and page logic.


Frequently Asked Questions (FAQ)

1.containIs the filter case sensitive?

Yes,containThe filter is case sensitive by default. For example,"AnQiCMS"|contain:"cms"It will returnFalseIf you need to perform a case-insensitive judgment, it is recommended to first convert the original string or substring through|loweror|uppera filter to uniform case and then compare.

2. Can I determine if a string contains any of multiple substrings?

Of course. You can use multiplecontainthe filter meetsiflabel'sorlogical operators together. For example:

{% if article.Title|contain:"Go语言" or article.Title|contain:"AnQiCMS" %}
    <p>这篇文章与Go语言或AnQiCMS相关。</p>
{% endif %}

If you need to determine whether it contains all the specified substrings, you can useandoperator.

3. Besides strings,containWhat data types can the filter check?

containThe filter is very flexible, it can check not only normal strings, but also:

  • array (slice): Determine if a certain value exists in the array.
  • (map) or structure: Check if a certain key name exists. For example,["Apple", "Banana"]|contain:"Apple"will returnTruewhile{ "name":"Alice" }|contain:"name"will be returnedTrue.

Related articles

What are the benefits of directly defining an array (`list`) in the AnQiCMS template? How to define it?

In the AnQiCMS template, we often encounter some scenarios where we need to display some small, relatively fixed list data, such as the featured functions of a page, the advantages of a product series, or auxiliary navigation links, etc.The traditional method may require creating a special content model on the backend, then publishing several data items, and finally calling through template tags.But this seems a bit繁琐 for those data that do not change often and are limited in quantity.

2025-11-08

How does the `add` filter implement flexible connection of text content?

In the Anqi CMS template world, we often need to dynamically combine different content blocks or data, whether it is the sum of numbers or the concatenation of text.At this time, the `add` filter acts as a flexible bridge, helping us easily achieve content concatenation, making the website display more vivid and personalized. ### Deep Understanding of `add` Filter: The Bridge Between Text and Data The `add` filter is a very practical feature in the Anqi CMS template engine, whose core function is to perform addition of numbers and concatenation of strings.It lies in its intelligent processing style

2025-11-08

How to format numbers or variables into a specified string format: common applications of the `stringformat` filter?

In the template development of Anqi CMS, we often need to display various data obtained from the background in a specific and beautiful format to website visitors.Whether it is the price of goods, the reading volume of articles, or the balance of users' points, the original presentation of data may not always be ideal.This is when the `stringformat` filter becomes a very useful tool.The `stringformat` filter helps us to format numbers, variables, and even more complex structures according to the predefined string pattern and output them.In short

2025-11-08

`trim`, `trimLeft`, `trimRight` filters specific usage scenarios and differences in AnQiCMS templates?

In AnQiCMS template development, handling and optimizing the display of page content is one of the daily tasks.We often need to process the data obtained from the backend to ensure that it is neat and meets expectations on the frontend.Among them, the cleaning of strings, especially the removal of redundant whitespace characters or specific characters, is a key factor in improving content quality and user experience.The AnQiCMS template system provides several very practical filters: `trim`, `trimLeft`, and `trimRight`.They each have their own unique uses and application scenarios.

2025-11-08

The role of the `count` filter in template data analysis for counting the occurrence of substrings?

In content operation, data analysis is an indispensable link.It can help us understand user behavior, evaluate content effectiveness, and guide future content strategy.AnQi CMS, with its flexible template engine syntax, provides us with powerful data processing capabilities, allowing us to perform some basic and practical data analysis directly at the template level.Among them, the `count` filter is like an efficient 'data detective' that helps us quickly understand the frequency of specific elements in the template data.Understand and make good use of this filter, it will greatly enhance our accuracy in content presentation and strategy formulation

2025-11-08

How to safely display rich text content containing HTML tags in AnQiCMS templates?

In website operation, we often need to display text content containing rich formats and interactive elements, which is what we usually call rich text.This content may contain bold, italic, links, images, and even tables with HTML tags.How can one ensure that these HTML tags are rendered correctly in the AnQiCMS template while also taking into account the website's security, which is a topic worth discussing.### Understand the default security mechanism of AnQiCMS template Firstly, we need to understand one of the core security designs of the AnQiCMS template system: by default

2025-11-08

The `safe` filter: when to use, what potential security risks need to be paid special attention to?

During the template development process of Anqi CMS, the way content is displayed is flexible and diverse, and one of the very important filters is `safe`. Understanding the working principle of the `safe` filter, when to use it, and the security considerations it may bring, is crucial for building a website that is both functional and secure. ### The core function of the `safe` filter First, let's understand a basic security mechanism of the Anqi CMS template engine: the default automatic escaping.

2025-11-08

The role of `escape` and `escapejs` filters in preventing XSS attacks or handling special characters?

In website content operation, the display method and security of the content are equally important.AnQi CMS is an efficient content management system that provides comprehensive considerations for website security, among which the `escape` and `escapejs` filters are important tools for us to combat network attacks and ensure the correct display of content.Understanding their role can help us better manage and publish content.

2025-11-08