How to combine AnQiCMS `if` logical judgment tags to implement conditional keyword replacement?

Calendar 👁️ 73

In the flexible and powerful template system of AnQiCMS, achieving high content customization is the key to improving user experience and meeting operational needs. Among them, combiningifLogical judgment tags for conditional keyword replacement can make our website content more intelligent and accurate. Whether it is to optimize SEO effects or to provide more attractive information in specific scenarios, this is a very practical skill.

Let's explore how to use this feature in AnQiCMS to bring new vitality to the website content.

Understanding core tools:ifTag and content processing

In the template syntax of AnQiCMS,ifTags are the foundation for logical judgments. They allow us to decide whether to execute a piece of code based on set conditions, or to choose one from multiple possibilities.Its basic structure is similar to the programming languages we are familiar with:

{% if 条件 %}
    <!-- 条件为真时执行的代码 -->
{% elif 其他条件 %}
    <!-- 第一个条件不满足,但其他条件为真时执行的代码 -->
{% else %}
    <!-- 所有条件都不满足时执行的代码 -->
{% endif %}

In order to implement keyword replacement, we need to make use of the filter function provided by AnQiCMS. Among which,replaceThe filter can help us replace the specified old word with a new one in the string, andcontainThe filter can be used to determine if the content contains a certain keyword, toifprovide a basis for tag judgment.

  • replaceFilter:{{ obj|replace:"旧词,新词" }}, it will be used toobjAll 'old words' in the variable are replaced with 'new words'.
  • containFilter:{{ obj|contain:"关键词" }}It will check,objwhether the variable contains the specified 'keyword' and returnTrueorFalse.
  • setTag:{% set myVar = "some value" %}This tag is very useful, it can help us define temporary variables in templates, making complex logic clearer.

Of course, to manipulate content, we first need to get it.archiveDetailUsed to obtain document details,categoryDetailGet category details,systemGet global settings and other tags, which are all our sources to obtain target contentobjAn important source.

Practical scenario: The application of conditional keyword replacement

ByifLabel, we can intelligently adjust the keywords on the page based on different content attributes or access context.This is more refined and dynamic than the 'Global Content Replacement' provided by the backend, which is usually used for unconditional, batch processing of global content.Template-level conditional replacement is performed before the content is rendered to the user's browser, based on specific rules and immediately.

Scene one: Keyword replacement based on classification

Assuming our website sells a variety of products, under the 'Mobile Accessories' category, we hope to replace the word 'high quality' in the product description with 'original factory quality' to emphasize its professionalism.

Inproduct/detail.htmlIn the product detail template, we can operate like this:

{# 首先获取当前产品的分类ID #}
{% archiveDetail currentCategoryId with name="CategoryId" %}

{% if currentCategoryId == 15 %} {# 假设“手机配件”分类的ID是15 #}
    {# 如果是手机配件分类,则替换关键词 #}
    {% archiveDetail productContent with name="Content" %}
    <div class="product-description">
        {{ productContent|replace:"高品质,原厂级品质"|safe }}
    </div>
{% else %}
    {# 其他分类则显示原始内容 #}
    {% archiveDetail productContent with name="Content" %}
    <div class="product-description">
        {{ productContent|safe }}
    </div>
{% endif %}

Here we go througharchiveDetailGot the category ID of the current document, thenifTag judgment, if it is the specified category, usereplaceFilter to replace. Remember to add.|safeFilter to ensure that HTML content is parsed correctly and not escaped into plain text.

Scenario two: Adjust keywords based on content characteristics

We may hope that if the article title contains the word 'tutorial', then in the article abstract, 'tutorial' should be replaced with a more specific 'operation guide' to enhance the attractiveness of the content.

Inarticle/list.htmlOr (article list template)article/detail.htmlIn (article detail template):

{% archiveList articles with type="list" limit="10" %} {# 假设在文章列表页 #}
{% for item in articles %}
    <div class="article-item">
        <h3><a href="{{item.Link}}">{{item.Title}}</a></h3>
        <p>
            {% set originalDescription = item.Description %}
            {% if originalDescription|contain:"教程" %}
                {# 如果摘要包含“教程”,则替换为“操作指南” #}
                {{ originalDescription|replace:"教程,操作指南" }}
            {% else %}
                {# 否则显示原始摘要 #}
                {{ originalDescription }}
            {% endif %}
        </p>
    </div>
{% endfor %}

In this example, we first usesettags to store the article description in a temporary variable, then usecontainThe filter determines whether to include a specific keyword and then decide whether to replace it.

Scenario three: Replace combined with custom fields.

AnQiCMS supports adding custom fields to content models. We can use these fields to control keyword replacement. For example, if the product model has a field namedIsFeaturedThe boolean custom field (whether recommended), we hope to replace the word "product" in its name when the product is marked as recommended with "recommended product".

AssumeIsFeaturedThe field is set to 'Single choice' in the background, with values 'Yes' or 'No'.

{# 在产品详情页,获取自定义字段“IsFeatured”的值 #}
{% archiveDetail isFeaturedValue with name="IsFeatured" %}

<h3>
    {% if isFeaturedValue == "是" %} {# 判断自定义字段的值 #}
        {{ archive.Title|replace:"产品,推荐商品" }}
    {% else %}
        {{ archive.Title }}
    {% endif %}
</h3>

We go through it directly herearchiveDetailTag to get custom fieldIsFeaturedThe value, and compare it with the string "is" to achieve conditional replacement.

Implementation steps and precautions

  1. Determine the replacement target: Clearly specify which template file (such asdetail.html,list.htmlWhich content field (such asTitle,Content,Descriptionor custom field) for conditional replacement.
  2. Locate the template file: According to the AnQiCMS template directory structure (design-director.md), find the corresponding template file to edit. For example, the article detail page is usuallyarticle/detail.html.
  3. Writingiflogic: Combine actual needs, useif/elif/elsebuild judgment conditions and nestreplaceFilter. If you need to judge the content early

Related articles

Use the `replace` filter to replace keywords in the website name, what are some practices?

In the daily operation of AnQiCMS, we often need to make flexible adjustments to the website content, especially to core elements such as the website name.In order to cope with the ever-changing marketing needs, or to optimize search engine optimization (SEO) more accurately, sometimes we hope to replace specific keywords in the website name dynamically on the front-end page without directly modifying the background configuration.At this time, the `replace` filter provided by the AnQiCMS template engine has become a very powerful tool.

2025-11-08

What is the priority of the `replace` filter operation in AnQiCMS, and will it conflict with template variables?

When using AnQi CMS for content operation, we often encounter the need to replace specific text on the page.Among them, the `replace` filter is a very practical tool in the template, but there are indeed some places where users are easy to confuse with the way the template variables themselves work and the "document keyword replacement" function provided by the system backend.Today, let's delve into the priority of the `replace` filter's replacement operation in AnQiCMS, as well as whether it will conflict with template variables.

2025-11-08

Does the `replace` filter break the structure of tags when processing strings containing HTML tags?

AnQi CMS provides us with great convenience with its powerful content management functions and flexible template mechanism.In daily operations, we often need to make batch modifications to website content, at which time filters like `replace` are particularly useful.However, when our string contains HTML tags, will this powerful `replace` filter treat it like plain text, thereby inadvertently destroying our meticulously designed page structure?

2025-11-08

How to unify the external link prefix displayed on the AnQiCMS page using the `replace` filter?

In website operation, the standardization of external links is often overlooked but is also very important.The prefix displayed on the unified page for external links, which not only helps enhance the professional image of the website, but also to some extent optimizes SEO performance, even facilitates subsequent data analysis or link management.AnQiCMS as a flexible content management system provides powerful template engine features, among which the `replace` filter is the tool to achieve this goal.

2025-11-08

Can the `replace` filter be used for the `set` variable defined in the AnQiCMS template?

In AnQiCMS template development, flexibly using various tags and filters is the key to achieving content customization display.When you need to define a variable in a template and process its content further, for example, string replacement, a common question is: can the `replace` filter be applied to variables defined through the `set` tag?The answer is affirmative.

2025-11-08

What to note when processing URL parameters with the AnQiCMS `replace` filter?

In AnQi CMS template development, the `replace` filter is a very flexible string processing tool that can help users quickly replace specific strings in text content.However, when its application scenarios involve handling URL (Uniform Resource Locator) parameters, we need to invest more thought and caution, as URL parameters have their own unique structure and encoding standards. ## Learn the basic functions of `replace` filter First, let's review the basic usage of the `replace` filter.

2025-11-08

How to use the `replace` filter to dynamically adjust the keyword density in page titles or `meta` descriptions?

In website content operation, page title (Title) and Meta description (Description) are key elements of search engine optimization (SEO).They not only directly affect the visibility and click-through rate of a website on the search engine results page (SERP), but also serve as the first window through which users convey the core content of the page.

2025-11-08

How to avoid errors when using the AnQiCMS `replace` filter to replace strings containing special characters?

AnQiCMS as an efficient and flexible content management system, provides a wealth of features to help us manage and display content.In daily operations, we often use template tags and filters to process data, where the `replace` filter is a very practical tool that can help us easily replace specific content in strings.

2025-11-08