How to conditionally display elements in a template based on whether the content contains specific keywords?

Calendar 👁️ 77

In website operation, we often hope that the content can be presented more intelligently to the visitors.For example, if a technical article mentions a specific product, we may want to automatically display the product's recommendation information at the top or side of the article;If the product description includes the phrase 'Limited Edition', we would like to add a prominent 'Limited' emblem next to the product image.This ability to conditionally display elements based on whether the content contains specific keywords can greatly enhance the user experience and operational efficiency of the website.

AnQiCMS as an efficient and flexible content management system has fully considered the needs of such dynamic content display.It combines a powerful template engine with rich built-in tags and filters, providing a convenient way to achieve this intelligent content presentation.

Why do we need to judge the display based on keywords?

Imagine if you were running an e-commerce website, for products described as "pre-sale", it may be necessary to display a countdown module on the page;If you are a self-media operator, if the hot news you publish contains 'exclusive report', you may wish to add a red corner mark below the article title.It will undoubtedly take a lot of time and effort to manually perform these operations for each article or product, and it is easy to make mistakes.And through the keyword judgment function of the AnQiCMS template, these elements can automatically display or hide according to the content, not only improving efficiency, but also ensuring the consistency of display.It makes the website content more 'vivid', able to automatically adjust the form of expression according to the subtle features of the content, thus better attracting the attention of users and guiding user behavior.

The basic condition judgment of AnQiCMS template:ifTags with powerful filters

AnQiCMS's template system adopts syntax similar to the Django template engine, with its core advantage lying in the intuitive conditional judgment logic and diverse filters. To implement displaying elements based on whether the content contains specific keywords, the following key components are mainly used:

FirstlyifLogical judgment label. It is the basis of all conditional displays, allowing us to decide whether to execute the code block in the template based on the truth or falsity of an expression. Its basic structure is{% if 条件 %} ... {% endif %}can also be combinedelifandelsefor multiple judgments.

is used to obtain page content tags, for example, in the article detail page, we usually usearchiveDetailLabel to get the title, content, keywords and other information of the current article.

The most critical is the powerful "filter" function provided by AnQiCMS.These filters can perform various operations on variables, including string operations, format conversion, etc. Among them,containThe filter is a powerful tool for keyword judgment. It can determine whether a string (or array, Map, etc.) contains a specified keyword and returns a boolean value (TrueorFalse), which is exactlyifThe judgment conditions required for the tag.

Practical demonstration: Step by step to implement keyword condition display

Now, let's look at a specific example to see how to conditionally display an element in the AnQiCMS template based on whether the content contains a specific keyword.Suppose we want to display a prominent 'Recommend using AnQiCMS' prompt below the article title on the article detail page if the article content mentions 'AnQiCMS'.

Step one: Get the content to be judged.

In the template file of the article detail page (usuallyarchive/detail.htmlIn a custom document template, we can usearchiveDetailtags to get the main content of the article. Usually, we will assign the content to a variable first for easy subsequent processing.

{% archiveDetail articleContent with name="Content" %}
{# articleContent 现在包含了文章的正文内容 #}

The second step: Introduce the core tool:containFilter

containThe filter is used specifically to determine if a string contains a specific substring. Its usage is very direct, passing the string to be checked through the pipe symbol|pass tocontainfollowed by the keyword to be searched.

For example:{{ articleContent|contain:"AnQiCMS" }}This will returnTrueorFalse.

Step 3: Combine usageifwith the tag andcontainFilter

Now, we will obtain the content,containFilters andifCombine the tags to implement conditional judgment.

{% archiveDetail articleContent with name="Content" %}
{% if articleContent|contain:"AnQiCMS" %}
    <div style="background-color: #e0f7fa; padding: 10px; border-left: 5px solid #00bcd4; margin-bottom: 20px;">
        <p style="font-weight: bold; color: #00838f;">💡 提示:本文内容涉及 AnQiCMS,推荐您深入了解这款高效易用的内容管理系统!</p>
    </div>
{% endif %}

In this code block:

  1. Firstly, we use{% archiveDetail articleContent with name="Content" %}Extract and store the main content of the current article.articleContentVariable.
  2. Then,{% if articleContent|contain:"AnQiCMS" %}this line of code judgesarticleContentDoes the variable contain the string “AnQiCMS”.
  3. If it contains (i.e., the condition is"),TrueThen{% if ... %}and{% endif %}the HTML code between them will be rendered on the page.
  4. If the article content does not contain "AnQiCMS", this prompt information will not be displayed on the page.

By such settings, your website will be able to intelligently display specific prompts based on the content of the articles, without manual intervention, greatly enhancing the convenience of operation and the attractiveness of the content.

Advanced Application and Flexible Expansion

This method of conditional judgment based on keywords can also be further expanded to meet more complex scene requirements:

  • Multi-keyword logical judgment: If you need to determine whether the content contains multiple keywords (such as "AnQiCMS" and "Go language"), you can useandconnect multiplecontainexpression:

    {% if articleContent|contain:"AnQiCMS" and articleContent|contain:"Go语言" %}
        {# 同时包含这两个关键词时显示 #}
    {% endif %}
    

    If it contains any of the keywords, then useor:

    {% if articleContent|contain:"AnQiCMS" or articleContent|contain:"内容管理系统" %}
        {# 包含其中任一关键词时显示 #}
    {% endif %}
    
  • Determine in the article list based on the title/abstract: In addition to the article content, you can also use in the article list page (usingarchiveListTags within, for each article title (item.Title) or description (item.Description) perform keyword judgment to add different tags or styles to list items.

  • Case-insensitive keyword matching: By default,containThe filter is case sensitive. If you need to ignore case, you can first uselowerThe filter converts both content and keywords to lowercase before making a judgment:

    {% set targetKeyword = "anqicms" %}
    {% if articleContent|lower|contain:targetKeyword %}
        {# 不区分大小写判断,无论原文是AnQiCMS、anqicms还是ANQICMS都会匹配 #}
    {% endif %}
    
  • Dynamic keyword list matchingIf you have a set of keywords to match, you can define a keyword array in the template, then iterate over the array to make a judgment, or concatenate the keywords in the array into a regular expression (if the AnQiCMS template supports regular expression matching), but forcontainIn terms of filters, it is more common to pass a single keyword directly. More advanced dynamic matching may require backend data support.

Summary

AnQiCMS with its concise and efficient template syntax and rich built-in features makes the dynamic content display of the website accessible. By using flexiblyifTags andcontainWe can easily implement conditional content display based on keywords, thereby injecting more intelligent operational strategies into the website.This ability can become a powerful tool to enhance your website's competitiveness, whether it is to improve user experience, optimize SEO, or fine-tune content marketing.


Frequently Asked Questions (FAQ)

1.containDoes the filter distinguish between uppercase and lowercase? If I want to perform a case-insensitive keyword search, what should I do?

Yes,containThe filter is case-sensitive by default. For example, checking if 'AnQiCMS' contains 'cms' will returnFalse. To perform a case-insensitive check, you can first uselowerThe filter converts the content to be checked and your keywords to lowercase, then usescontainto make a judgment. For example:{% if articleContent|lower|contain:"anqicms" %}.

2. I want to judge whether the content contains multiple keywords at the same time, such as must contain both "A" and "B", or it is enough to contain "A" or "B". Does AnQiCMS template support this logical judgment?

The AnQiCMS template fully supports complex logical judgments. If you need to include multiple keywords (i.e., 'AND' relationship), you can useandoperator to connect multiplecontainexpression:{% if content|contain:"关键词A" and content|contain:"关键词B" %}. If you only need to include any of the keywords (i.e., 'or' relationship), you can useoroperator:{% if content|contain:"关键词A" or content|contain:"关键词B" %}.

3. Besides the article content (Content), which fields in AnQiCMS can I judge with keywords to conditionally display elements?

In addition to the article content, you can also perform keyword judgment on other text fields. For example, on the article detail page, you can usearchiveDetailtags to get the title of the article (Title), description (Description) or keywords (KeywordsField judgment. On the article list page, you can also judge each article item (itemThe title of (item.Title) or description (item.DescriptionField judgment. Through `archiveParams'

Related articles

How does AnQi CMS support displaying multilingual switch links and hreflang tags in the front-end template?

Today, with the increasing trend of globalization, many websites need to provide services to users from different countries and regions.This means that the website must not only support content display in multiple languages but also ensure that search engines can correctly identify these different language versions, thereby enhancing the visibility in the international market.AnQiCMS as a practical content management system provides strong and flexible support in this aspect.

2025-11-09

How to use the 'Remove logical tag line occupation' feature to clean up extra blank lines rendered by the template?

When using AnQi CMS to manage a website, we all hope that the page presented to the visitor is both beautiful and efficient.The page loading speed and the neatness of the source code not only affect the user experience, but also have a subtle but important impact on search engine optimization (SEO).You may have encountered such a situation in the process of template development: although the template code looks neat, there are always some unwanted blank lines in the rendered HTML source code.

2025-11-09

How to define and assign variables in a template to temporarily control the display logic of content?

In AnQi CMS template development, flexibly defining and assigning variables is the key to dynamic display of website content and personalized layout.By cleverly using variables, we can temporarily adjust the presentation of content, making the template not only able to carry basic data display but also able to present a rich and varied display logic according to specific conditions.This article will deeply explore how to define and assign variables in AnQiCMS templates, as well as their actual application in controlling the display logic of content.### The Foundation of Template Variables

2025-11-09

What methods does AnQiCMS provide for template developers to debug variable output and structure type?

When developing templates in Anqi CMS, understanding and debugging variable output and data structure types is the key to improving efficiency.Although the AnQiCMS template engine (similar to Django or Blade syntax) is intuitive and easy to use, mastering some debugging techniques can make you twice as effective when encountering problems.We usually understand the variables and data structures in the template through the following ways. ### 1.

2025-11-09

How to accurately截取string or HTML content and add an ellipsis to adapt to layout requirements?

In website content operation, we often encounter such needs: In order to keep the page layout neat and the reading experience smooth, it is necessary to truncate the long text (whether it is plain text or content containing HTML tags) and add an ellipsis at the end.AnQiCMS provides very practical template filters that can help us accurately complete this task while ensuring that the content display is both beautiful and does not destroy the HTML structure.### Understanding the extraction requirements and the solution of AnQiCMS Imagine, in an article list

2025-11-09

Does AnQiCMS support automatically appending a thumbnail parameter to the image address for display?

In website content operation, images are undoubtedly an important element to attract visitors, and the loading speed and display effect of images directly affect the user experience.To optimize website performance, it is particularly important to use thumbnails reasonably.Many website systems generate or call different-sized images by appending parameters to the image address.How does AnQi CMS handle this aspect?Does it support automatically appending a thumbnail parameter to the image URL to display?

2025-11-09

How to control the display form of the front-end link of category, document, and single page through custom URL alias?

In website operation, the display form of the front-end link (URL) is crucial for user experience, search engine optimization (SEO), and brand image.A concise, meaningful, and well-structured URL can not only help users better understand the content of the page but also improve the efficiency of search engine crawling and ranking.AnQiCMS (AnQiCMS) fully understands this need and provides a flexible custom URL alias function, allowing us to accurately control the link display of categories, documents, and single pages on the website's front end according to our needs.

2025-11-09

How to dynamically display the document title of the current page in AnQiCMS templates?

In AnQi CMS template design, dynamically displaying the document title of the current page is a basic and important function.It not only concerns the intuitive experience of users when browsing the website, but is also an indispensable part of search engine optimization (SEO) strategy.AnQi CMS provides a simple and efficient way to meet this requirement, let's explore how to flexibly use it in templates.

2025-11-09