How to determine whether a string, array, or object in AnqiCMS template contains a specific keyword and display content dynamically based on this?

Calendar 👁️ 62

In AnqiCMS, flexibly judging and dynamically displaying information based on content is the key to improving website user experience and SEO effectiveness.Imagine a website that automatically displays related purchase links based on whether an article mentions a specific product; or recommends different sidebar content based on the category the user is in.This not only makes your website smarter, but also greatly improves the efficiency of content operation.

The AnqiCMS template engine provides powerful features to easily implement these dynamic logic.It borrows the syntax of the Django template engine, making conditional judgment and data traversal intuitive.Today, let's delve into how to determine whether a string, array, or object in the AnqiCMS template contains a specific keyword and display content dynamically based on this.

Understand the judgment logic in AnqiCMS templates

The core of AnqiCMS templates lies in their concise and powerful tags. Variables are usually enclosed in double curly braces.{{变量}}wrap, while logical control (such as conditional judgment and loop) uses single curly braces and percentage signs{% 标签 %}when it is necessary to display content dynamically according to dataiflogical judgment tag{% if ... %}It is our basic tool, it allows us to define conditions and execute corresponding template code when the conditions are true.

However, just havingifThe label is not enough.We need a method to determine whether a variable contains a specific value.containfilter.

Core tool:containFilter

containThe filter is a tool specifically used in the AnqiCMS template engine to detect whether the content contains specific keywords.Its functionality is very powerful, not only can it determine whether a line of string contains a keyword, but it can also detect whether an element exists in an array (slice), and even whether a key exists in a key-value pair (map) or a structure (struct).

containThe basic usage of the filter is very simple: you just need to pass the variable to be checked through the pipe character|pass tocontainFilter, and specify the keyword you want to count after the colon.:and then specify the keyword you want to search for.

For example:{{ obj|contain:"关键词" }}

This filter will return a boolean value (TrueorFalseIf the keyword is found, it returnsTrue; otherwise, it returnsFalse. With this boolean value, we can combineiftags to easily implement dynamic content display.

The practical application scenario: display dynamically according to content

Let's look at some specific examplescontainThe application of filters under different data types.

1. Determine if a text string contains a specific keyword

This is the most common application scenario. For example, you want to display a special promotional icon or link if the title or description of an article contains the words 'discount'.

{% archiveDetail article with name="Description" %} {# 获取当前文章的描述内容 #}

{% if article|contain:"优惠" %}
    <span class="promo-badge">限时优惠!</span>
    <a href="/promotions" class="btn btn-primary">立即查看优惠商品</a>
{% else %}
    <a href="/products" class="btn btn-secondary">浏览所有商品</a>
{% endif %}

In this example,archiveDetailThe tag obtained the description of the current page article. Then, we usearticle|contain:"优惠"To determine if the description string contains the word "discount". If it does, display promotional information; otherwise, display a normal product link.

2. Determine if a specific element exists in the array (Slice)

Sometimes, you will encounter list type data, such as the Tag list of an article.You may want to display a 'NEW' corner mark if the article is marked as 'new'.

AssumetagsIt is an array containing strings, for example.["GoLang", "CMS", "SEO"].

{% tagList tags with itemId=archive.Id limit="10" %} {# 获取当前文章的标签列表 #}

{% if tags|contain:"新品" %}
    <span class="new-badge">NEW</span>
{% endif %}

{# 也可以遍历标签列表,判断每个标签的Title属性 #}
{% for tag in tags %}
    {% if tag.Title|contain:"新品" %}
        <span class="new-badge">NEW</span>
    {% endif %}
{% endfor %}

here,tagListThe tag fetched all the tags associated with the current article.tags|contain:"新品"It will check if the element 'New Product' is present in the array of tag names. Of course, iftagsis an array of objects (such astag.TitleYou may need to traverse the array and judge a specific attribute of each element.

3. Determine whether a specific key name exists in the object (Map/Struct)

Custom fields in AnqiCMS are very flexible, you can add any custom fields to articles or products through the content model.Assuming you have added a custom field named "VideoLink" to the product model, used to store the link of the product demonstration video.If this field exists, you would want to embed a video player on the page.

{% archiveParams params with sorted=false %} {# 获取当前文章的所有自定义参数,以map形式返回 #}

{% if params|contain:"VideoLink" %}
    <div class="product-video">
        <h3>产品演示</h3>
        <iframe src="{{ params.VideoLink.Value }}" frameborder="0" allowfullscreen></iframe>
    </div>
{% else %}
    <p>暂无产品演示视频。</p>
{% endif %}

In this example,archiveParamsThe tag retrieved all the custom parameters of the article.params|contain:"VideoLink"the judgment.paramsDoes this object contain a key named 'VideoLink'. If it exists, we can go throughparams.VideoLink.ValueGet the video link and embed the player.

Flexible combination: Make content presentation more intelligent and accurate

containthe filter meetsif/else/elifThe combination of tags can achieve very complex dynamic content logic.For example, you can display different sidebar recommended articles, call different CSS styles, and even change the overall layout of the page based on different keywords in the article content.

{% archiveDetail articleContent with name="Content" %} {# 获取文章完整内容 #}

{# 如果内容包含“联系我们”且包含“定制服务”,显示定制服务表单 #}
{% if articleContent|contain:"联系我们" and articleContent|contain:"定制服务" %}
    <div class="custom-service-form">
        <h4>定制服务需求提交</h4>
        {% guestbook fields %}
            {# 这里嵌入留言表单的字段 #}
        {% endguestbook %}
    </div>
{# 如果只包含“联系我们”,显示基础联系信息 #}
{% elif articleContent|contain:"联系我们" %}
    <div class="contact-info">
        <h4>联系我们</h4>
        <p>电话:{% contact with name="Cellphone" %}</p>
        <p>邮箱:{% contact with name="Email" %}</p>
    </div>
{% else %}
    <p>如果您有任何疑问,请随时<a href="/contact">联系我们</a>。</p>
{% endif %}

By such a combination, your

Related articles

How to display detailed information of image resources on the front page, such as file name, size, and image address?

When using AnQiCMS to manage website content, images are undoubtedly an important element in enhancing page attractiveness.We often need to display not only the image itself on the front-end page, but also further details about the image, such as their filenames, sizes, and storage addresses.This is very helpful for visitors to understand the background of the image, to reference the content, or to manage and download the image.

2025-11-09

How to display specific content or member permission prompts for different user groups on the front page of Anqi CMS?

In website operation, providing differentiated content or services for different user groups is an important strategy to enhance user experience and achieve content monetization.AnQiCMS (AnQiCMS) understands this need, built-in powerful user group management and VIP system, allowing you to easily implement personalized content display and permission control on the front page. ### Flexible User Groups and Permission System One of the core strengths of Anqi CMS is its flexible user group and VIP system.In the background, you can create multiple user groups, such as "Regular User", "Registered Member", "VIP Member"

2025-11-09

How to batch regenerate the thumbnails of AnqiCMS to adapt to the new display size requirements of the front page?

The display effect of image materials is crucial during website operation.Sometimes, due to website template updates, design style adjustments, or considerations for optimizing performance, the front-end page of the website may require new display sizes for image thumbnails.In this case, how can a large number of images uploaded to AnqiCMS (AnqiCMS) be generated into appropriate thumbnails according to new size requirements, rather than manually processing one by one, which has become a concern for many users.AnqiCMS fully considers the actual needs of content operators and built-in convenient thumbnail batch processing function

2025-11-09

How to configure the image processing method (Webp, compression, thumbnail) in AnqiCMS content settings to optimize front-end loading speed and display quality?

In the era where content is king, the loading speed and display quality of website images have a significant impact on user experience and search engine optimization (SEO).High-quality images, if they load slowly or are blurry, not only may deter visitors, but may also affect the website's ranking in search engines.Luckily, AnqiCMS provides a series of powerful and flexible image processing features to help us easily meet these challenges.Next, we will delve deeper into how to cleverly configure the image processing method in AnqiCMS content settings, including WebP

2025-11-09

How can I truncate a string or HTML content in AnqiCMS template and add an ellipsis to control the display length?

In website operation, the way content is presented has a crucial impact on user experience and information transmission efficiency.Whether it is the introduction of the article list, the abstract of the product description, or other text content that needs to be previewed, reasonable control of the display length and the use of ellipses can not only maintain the page's neat and beautiful appearance, but also guide users to click and view more details.AnqiCMS as an efficient and flexible content management system, provides a variety of powerful template tags and filters, making the control of content length extremely simple and intelligent.Why do we need to truncate content and add an ellipsis

2025-11-09

How to automatically parse a URL string into a clickable a tag in AnqiCMS template for convenient browsing?

When operating a website, we often add some URLs in articles, product descriptions, or single-page content, which may be recommended external resources or references to other content within the site.But if these URLs are just displayed in plain text, users will have to copy and paste to access them, which is inconvenient and also affects the reading experience.AnqiCMS has fully considered this point and provided us with a very convenient way to automatically convert plain text URLs in the content into clickable links, greatly enhancing the convenience of user browsing and the professionalism of the website.

2025-11-09

How to display traffic or crawler access data charts on the front end of AnqiCMS's background data statistics function?

Understanding website traffic and user behavior is crucial for operators.AnqiCMS as an efficient enterprise-level content management system provides detailed data statistics and crawling monitoring functions in the background.This data can not only help us analyze the performance of the website and optimize the content strategy, but also has the potential to provide more intuitive information to users or visitors in specific scenarios through the display of charts on the front end.

2025-11-09

How can you dynamically obtain and display the current year or other time information in the AnqiCMS template?

In website operation, we often need to dynamically display the current year, date, or time on the page, such as the copyright information in the footer, the publication or update time of articles, etc.This information, if manually updated, is not only time-consuming and labor-intensive, but also prone to errors.Fortunately, AnqiCMS provides a concise and efficient method for you to easily implement the acquisition and display of these dynamic time information in the template.### Dynamically retrieve and display the current year or other time information In the AnqiCMS template, to retrieve and display the current year or any format of the current time, we can use the built-in

2025-11-09