How to check if the article content in the AnQiCMS template contains specific keywords and display conditions based on this?

Calendar 👁️ 73

In website content operation, we often need to flexibly adjust the display of the page according to the actual content of the article.For example, if an article mentions a specific product or event, we may want to highlight related purchase links or promotional information on the page;If the content of the article involves sensitive topics, it may be necessary to add additional disclaimers.This requirement for conditional display based on article content can be fully realized in AnQiCMS (AnQiCMS) templates.

The AnQi CMS uses a template engine syntax similar to Django, which makes its templates well-readable and powerful in logical processing.In the AnQiCMS template, we can easily check whether the article content contains the keywords we have preset by using specific tags and filters, and control the display of page elements according to the check results.

How to check if a specific keyword is contained in the article content of the AnQiCMS template and display conditions based on this?

To achieve this goal, we need to use several core features of the Anqi CMS template:

  1. archiveDetailTag: Used to obtain the detailed information of the current or specified article, including the content of the article.
  2. settag (orwith): Used to define and assign variables in the template, so that we can store the obtained article content and judgment results.
  3. containFilterThis is a key tool for keyword checking, which can determine whether one string contains another substring.
  4. iflogical judgment tagAccording tocontainThe filter's judgment result (true or false) to execute different template code blocks.

Below, we will elaborate on how to implement this feature in the AnQiCMS template through specific steps and code examples.


1. Obtain the article content

Firstly, we need to obtain the detailed content of the current article in the template. For example, on the article detail pagearchive/detail.html),archiveDetailTags can help us obtain the article'sContentField. We usually assign the obtained content to a variable for subsequent operations.

{# 获取当前文章的Content内容,并赋值给名为 articleContent 的变量 #}
{% archiveDetail articleContent with name="Content" %}

{# 此时,articleContent 变量中就包含了文章的正文HTML内容 #}

Please note,articleContentThe variable stores the complete article content containing HTML tags. When displaying the article content in actuality, it is usually necessary to add|safeA filter to ensure that HTML tags can be correctly parsed by the browser and not displayed as escaped.


Second, define the keywords to be checked and make judgments.

Next, we need to determine the specific keywords to be checked and usecontainjudge.articleContentwhether they are included in it.

containThe filter is very intuitive, and its basic usage is{{ obj|contain:关键词 }}which will return a boolean value (TrueorFalseIndicatesobjWhether it contains the specified关键词.

We can combinecontainAssign the judgment result of the filter to a new variable, and then combineifTags for conditional display.

1. Check a single keyword

Assuming we want to check if the article content contains the keyword "Time-limited promotion":

{# 假设我们正在文章详情页 template/archive/detail.html #}

{# 步骤一:获取文章内容并赋值给 articleContent 变量 #}
{% archiveDetail articleContent with name="Content" %}

{# 步骤二:定义要检查的关键词 #}
{% set targetKeyword = "限时优惠" %}

{# 步骤三:使用 contain 过滤器检查文章内容是否包含该关键词,并将结果赋值给 hasOffer 变量 #}
{% set hasOffer = articleContent|contain:targetKeyword %}

{# 步骤四:根据 hasOffer 的值进行条件显示 #}
{% if hasOffer %}
    <div class="promo-banner" style="background-color: #fff3cd; padding: 10px; border: 1px solid #ffeeba; margin-bottom: 20px;">
        <p style="color: #856404; font-weight: bold;">🎉 注意:本文可能包含 <span style="color: red;">{{ targetKeyword }}</span> 信息,不容错过!</p>
        {# 您可以在这里放置一个醒目的促销链接或活动详情 #}
        <a href="/promo-page" style="color: #007bff; text-decoration: underline;">查看最新优惠活动 →</a>
    </div>
{% endif %}

{# 显示文章正文 #}
<div class="article-main-content">
    {{ articleContent|safe }}
</div>

In this example, ifarticleContentContains the string

2. Check multiple keywords (any one of which is sufficient)

If we need to check multiple keywords, as long as the article content contains any one of them, it will be displayed under certain conditions, and we can useorlogical operators to connect multiplecontainjudgments together:

{% archiveDetail articleContent with name="Content" %}

{% set keyword1 = "免费试用" %}
{% set keyword2 = "新用户福利" %}
{% set keyword3 = "体验版" %}

{# 只要包含任意一个关键词,hasFreebie 就为 True #}
{% set hasFreebie = articleContent|contain:keyword1 or articleContent|contain:keyword2 or articleContent|contain:keyword3 %}

{% if hasFreebie %}
    <div class="freebie-alert" style="background-color: #d1ecf1; padding: 10px; border: 1px solid #bee5eb; margin-bottom: 20px;">
        <p style="color: #0c5460;">✨ 本文提及 {{ keyword1 }}、{{ keyword2 }} 或 {{ keyword3 }},快来领取您的专属福利!</p>
        <a href="/free-trial" style="color: #007bff; text-decoration: underline;">立即前往 →</a>
    </div>
{% endif %}

<div class="article-main-content">
    {{ articleContent|safe }}
</div>

3. Check multiple keywords (all must be met)

If it is required that the content of the article must contain all specified keywords before displaying the condition, you can useandLogical operators:

{% archiveDetail articleContent with name="Content" %}

{% set reqKeyword1 = "AnQiCMS" %}
{% set reqKeyword2 = "安装教程" %}
{% set reqKeyword3 = "Go语言" %}

{# 只有同时包含所有关键词,isComprehensive 就为 True #}
{% set isComprehensive = articleContent|contain:reqKeyword1 and articleContent|contain:reqKeyword2 and articleContent|contain:reqKeyword3 %}

{% if isComprehensive %}
    <div class="tech-note" style="background-color: #d4edda; padding: 10px; border: 1px solid #c3e6cb; margin-bottom: 20px;">
        <p style="color: #155724;">✅ 本文详细介绍了 <span style="font-weight: bold;">{{ reqKeyword1 }} 的 {{ reqKeyword2 }}</span>,并且强调了其 <span style="font-weight: bold;">{{ reqKeyword3 }}</span> 的技术背景。对技术感兴趣的您请仔细阅读!</p>
    </div>
{% endif %}

<div class="article-main-content">
    {{ articleContent|safe }}
</div>

Scenario Thinking

This conditional display function based on keywords has a wide range of applications in actual operation:

  • Personalized Recommendations and MarketingIf a product model is mentioned in the article, a sales link to the product can be automatically inserted at the bottom of the article

Related articles

How to control the automatic escaping of HTML tags with the `autoescape` tag in AnQiCMS templates?

In the AnQiCMS template system, our daily content display core is inseparable from the handling of HTML tags.To ensure the security of the website, AnQiCMS defaults to automatically escaping variables output in templates.This mechanism effectively prevents the injection of malicious code, such as common cross-site scripting attacks (XSS).However, in some scenarios, we may need to display rich text content that includes HTML tags, at this point we need to understand how to flexibly control this automatic escaping function.### Automatically Escaped

2025-11-09

How can AnQiCMS templates safely display user-submitted rich text content to prevent potential XSS attacks?

During website operations, displaying rich text content submitted by users, such as article comments, forum posts, or blog content, is an unavoidable requirement.However, there may be malicious scripts hidden in these contents, and if they are displayed without precautions, it may lead to cross-site scripting (XSS) attacks, posing potential threats to website visitors.AnQiCMS (AnQiCMS) has fully considered this security risk in its design and provides a series of mechanisms through its template engine to help us safely handle this type of rich text content.

2025-11-09

What are the respective application scenarios of the `striptags` and `removetags` filters when cleaning HTML code in AnQiCMS templates?

In AnQiCMS template design, we often encounter situations where we need to clean up or simplify the HTML code in the content.This is not just for beauty, but also to ensure the correct display of content, improve page loading efficiency, and even prevent potential security risks.The Aqie CMS provides two very practical filters: `striptags` and `removetags`.Although they are all related to the removal of HTML tags, each has a clear application scenario.### `striptags`

2025-11-09

How to determine whether to truncate text and add an ellipsis (...) in AnQiCMS templates based on content length?

In AnQiCMS website content operation, how to elegantly handle long text content to make it both beautiful and complete on the page is the key to improving user experience.Especially on the list page, card display, or introduction area, overly long text often leads to layout confusion and affects the overall visual effect.AnQiCMS' powerful template engine provides various flexible ways to solve this problem, the most commonly used being the function of text truncation and adding ellipses.The AnQiCMS template system borrows the syntax of the Django template engine

2025-11-09

How to judge whether the current item is the first or last item in the `for` loop in AnQiCMS template?

In AnQiCMS template development, we often encounter situations where we need to display data in a list loop, such as article lists, product categories, navigation menus, etc.In these loops, sometimes we need to treat the first or last item in the list specially, such as adding unique CSS styles, displaying different content, or cleverly handling the separators between list items.AnQiCMS uses a syntax similar to the Django template engine, providing us with a very intuitive and powerful tool to solve these common template logic problems.### Core Mechanism

2025-11-09

How to implement the `cycle` tag to alternate the display of different styles or data in AnQiCMS templates?

AnQiCMS provides many practical tags for template development, making content display more flexible and efficient.Among them, the `cycle` tag is such a clever tool that it can help us achieve the alternation of data or styles in loops, making the page content more dynamic and visually attractive. ### Understanding the `cycle` tag: Sequence controller in loops In web design, we often encounter situations where we need to apply different styles to repeating elements or display different types of data in a specific order. For example

2025-11-09

How to skip certain items in the `for` loop of the AnQiCMS template based on specific conditions?

In AnQiCMS template development, we often need to display a series of contents, such as article lists, product lists, or navigation menus.But often, we do not want to display all the data at once, but rather hope to skip a part of it according to certain specific conditions, making the final content displayed more accurate and in line with the user's needs.AnQiCMS uses a syntax similar to the Django template engine, which provides a powerful and flexible tool for us to implement this conditional skipping.To implement `for`

2025-11-09

How to judge whether a custom field exists in the AnQiCMS template and conditionally render according to its value?

In AnQiCMS template development, flexibly displaying content is the key to improving user experience and website professionalism.Among them, judging custom fields and rendering conditions based on their values is an indispensable skill to achieve this goal.In this way, you can ensure the precise display of page content, avoid displaying empty values, or dynamically adjust the page layout and functionality based on specific data.### Understanding AnQiCMS Custom Fields and Their Retrieval Methods in Templates AnQiCMS is a powerful content management system

2025-11-09