In website operation, we often encounter such needs: to decide how to display page elements based on whether the content contains a specific word, such as highlighting some text, or only displaying a module when certain conditions are met.The AnQiCMS template system provides flexible filter functions to help us easily implement these keyword-based judgments.This article will delve into how to efficiently and accurately determine whether a line of text in the AnQiCMS template contains a specific keyword.
UsecontainFilter for keyword judgment
The most direct and recommended method is to usecontainThe filter is used specifically to determine whether a string, an array (slice), or even a key-value pair (map) or a struct exists with the specified keyword or key name.It returns a boolean value (TrueorFalseIt is very suitable for conditional judgment with the template{% if %}tag usage
Assuming we have a variablepageContentStoring the main content of the web page, we want to know if this content mentions the word "AnQi CMS". We can use it like thiscontainFilter:
{% set pageContent = "欢迎使用安企CMS(AnQiCMS),这是一款强大的内容管理系统。" %}
{% if pageContent|contain:"安企CMS" %}
<p>恭喜!内容中包含关键词“安企CMS”!</p>
{% else %}
<p>抱歉,内容中未找到关键词“安企CMS”。</p>
{% endif %}
In the above example, ifpageContentIf the string contains “AnQi CMS”, then it will display the phrase “Congratulations!”.containThe strength of the filter lies not only in its ability to judge strings, but also in its support for various data types.
1. Determine if the string contains the keyword:This is the most common usage, for example, to check an article