How to judge whether a string contains a certain keyword in AnQiCMS template and display the result?

Calendar 👁️ 72

In website operation, we often encounter such needs: dynamically adjusting the display method of content based on specific information of web page content.For example, if an article title contains keywords such as 'promotion' or 'event', we may want it to automatically display a prominent tag;Or, in order to check content for sensitive words and ensure user experience, it is necessary to check if certain sensitive words exist in the article and handle them accordingly.

The Anqi CMS is a powerful and flexible content management system that provides intuitive template tags and filters, making dynamic judgments and displays very simple.This article will introduce in detail how to judge whether a string contains a certain keyword in the AnQiCMS template, and implement various content operation strategies based on this.


1. Core Solution: UtilizecontainFilter keyword judgment

The most direct and commonly used method in the AnQiCMS template system is to usecontainA filter that can check if a string (or an array, key-value pair, etc.) contains a specified keyword (substring) and return a boolean value (TrueorFalse)

Basic usage:

containThe use of the filter is very intuitive, it accepts a keyword as a parameter and applies it to the target string.

{{ 目标字符串|contain:"关键词" }}

For example, to determine if an article titlearticle.Titlecontains the word 'Promotion':

{{"我们的AnQiCMS最新功能"|contain:"AnQiCMS"}} {# 这将输出 True #}
{{"这是一篇普通文章"|contain:"促销"}} {# 这将输出 False #}

Combine conditional judgment{% if %}Display result:

due tocontainThe filter returns a boolean value, which is used for conditional judgment tags in the template{% if %}Combined with, it can achieve the display of dynamic content.

Suppose you want to display a 'Hot' corner mark when the article title contains the words 'Hot':

{% if article.Title|contain:"热门" %}
    <span class="badge badge-hot">热门</span>
{% endif %}
<h2 class="article-title">{{ article.Title }}</h2>

Store the judgment result in a variable{% set %}:

In some cases, you may need to store the judgment result in a temporary variable so that it can be reused in multiple locations of the template or to perform more complex logical judgments. At this time, you can use{% set %}.

{% set isSpecialOffer = article.Description|contain:"限时优惠" %}

{% if isSpecialOffer %}
    <p class="promo-message">🎉 限时优惠中,抓住机会!</p>
{% endif %}

<div class="product-description">
    {{ article.Description }}
</div>

containFilter support for arrays and key-value pairs:

It is worth mentioning,containThe filter is not limited to strings. It can also be used to check if a value exists in an array or if a key exists in a key-value pair (map/struct).

  • Check the array:
    
    {% set tags = ["CMS", "Go", "内容管理", "企业站"] %}
    {% if tags|contain:"内容管理" %}
        <p>文章包含“内容管理”标签。</p>
    {% endif %}
    
  • Check the key name (for a struct or map):
    
    {# 假设 article.Extra 是一个包含自定义字段的 map 或 struct #}
    {% if article.Extra|contain:"author" %}
        <p>此文章有作者信息。</p>
    {% endif %}
    

Part two: More keyword processing filters

exceptcontain,AnQiCMS also provides other practical filters that can help you process keywords more finely related to the features.

  1. countFilter: Count the number of times keywords appearIf you not only want to know if a keyword exists, but also how many times it appears,countThe filter will be very useful.

    {% set keywordCount = archive.Content|count:"安企CMS" %}
    {% if keywordCount > 0 %}
        <p>文章内容中“安企CMS”一词出现了 {{ keywordCount }} 次。</p>
    {% endif %}
    

    This is very convenient for analyzing keyword density or for counting mentions of specific content in multiple places.

  2. indexFilter: Get the position of the first occurrence of the keyword indexThe filter returns the starting position (index) of the first occurrence of the keyword in the string. If the keyword does not exist, it returns -1.

    {% set firstOccurrence = article.Title|index:"活动" %}
    {% if firstOccurrence != -1 %}
        <p>“活动”一词在标题中首次出现在第 {{ firstOccurrence }} 个位置。</p>
    {% else %}
        <p>标题中不包含“活动”一词。</p>
    {% endif %}
    

    Please note when handling strings containing Chinese characters,indexThe filter may count a Chinese character as multiple bytes when calculating positions, which depends on its underlying implementation, so the returned index may not be the character number position you intuitively understand.

  3. replaceFilter: Replace keywords in stringsWhen you need to modify keywords in strings,replacethe filter comes into play. It can replace old keywords with new content.

    {% set originalTitle = "安企CMS:高效内容管理" %}
    {% set newTitle = originalTitle|replace:"安企CMS,AnQiCMS" %}
    <p>原标题:{{ originalTitle }}</p>
    <p>新标题:{{ newTitle }}</p>
    

    This feature is very useful in scenarios such as sensitive word filtering, keyword highlighting, and brand name unification. For example, to highlight a specific word, you can replace it with a version containing HTML tags:

    `twig

Related articles

How to optimize the page layout display using AnQiCMS template inheritance (`extends`) and inclusion (`include`) tags?

In website construction, how to organize the page structure efficiently to make the code reusable and easy to maintain is the key to improving development efficiency and project quality.AnQiCMS has fully considered this point, providing powerful template inheritance (`extends`) and template inclusion (`include`) tags, allowing us to build websites like building blocks, easily realizing complex page layout and display optimization.

2025-11-09

How to automatically replace and display anchor text in article content in AnQiCMS?

In website operation, anchor text is an important element that connects different pages, enhances content relevance, and optimizes search engine rankings.A well-crafted anchor text can not only guide users to discover more relevant information but also help search engines better understand the content and structure of the page and website.For those of you who use AnQiCMS (AnQiCMS) to manage content, the system provides an efficient and intelligent mechanism to automatically convert keywords in the article content into linked anchor text, thereby greatly improving the efficiency and effectiveness of content operation.

2025-11-09

How to add captcha functionality to the AnQiCMS comment form to reduce the display of spam comments?

In website operation, spam comments are undoubtedly a headache.They not only affect the user experience of the website, dilute high-quality discussion content, but may also harm the website's SEO performance in an invisible way, even occupying valuable server resources.Faced with increasingly intelligent spam comment robots, we need more effective defense measures.Fortunately, AnQiCMS provides a simple and powerful solution - adding a captcha feature to the comment form, which can significantly reduce the intrusion of spam comments.

2025-11-09

How to display the related article list of the `tagDataList` tag in AnQiCMS according to the specified Tag ID?

Manage and display content in AnQi CMS, especially when it is necessary to aggregate articles based on specific themes or keywords, the Tag feature is particularly important.It can not only help visitors quickly find the content they are interested in, but also effectively improve the internal link structure and SEO performance of the website.Today, let's delve into a very practical template tag in AnQiCMS: `tagDataList`, and see how it accurately displays a list of related articles based on the specified Tag ID.

2025-11-09

How to format a `time.Time` type variable into a readable date string in GoLang in AnQiCMS?

In AnQiCMS, managing website content often involves the need to display dates and times, such as the publication time of articles, update time, or the last login time of users, etc.These time data are typically stored as `time.Time` type in the GoLang backend.When they are passed to the front-end template, if not properly formatted, they may be displayed as a string of hard-to-understand timestamps or the default Go language format, which is obviously not in line with the needs of the visitors we show.

2025-11-09

How to implement custom JSON-LD structured data in AnQiCMS templates to optimize search results display?

In today's digital marketing environment, having high-quality content is not enough. How to make search engines better understand and display this content is becoming increasingly important.Structured data, especially JSON-LD, is a powerful tool at our disposal that can help our website present more rich and attractive forms in search results, which is what we often call 'rich snippets'.

2025-11-09

How does AnQiCMS's `urlizetrunc` filter truncate long URLs and display an ellipsis in the link?

The AnQiCMS `urlizetrunc` filter: Allows long URLs to elegantly transform into ellipses In daily website operations, we often need to reference external links in articles, comments, or product descriptions.These links may be intended to provide references, guide users to access related pages, or display product videos, etc.However, sometimes these URLs can be very long, not only occupying a large amount of page space, affecting the overall layout aesthetics, but also reducing the reading experience of the content.

2025-11-09

How to remove HTML tags in AnQiCMS template and display only plain text content?

In AnQiCMS content management practice, sometimes we encounter the need: to extract pure text information from documents containing rich formats (such as bold, italic, images, links, etc.).This may sound contradictory, content management systems are inherently committed to the diverse display of content, why would one still 'strip' these formats?

2025-11-09