How to replace a specific keyword in a string with another keyword and display it in AnQiCMS?

During the operation of a website, we often encounter the need to flexibly adjust specific text on the page.Sometimes it's to correct a typo, sometimes it's to unify brand terms, or just for A/B testing.AnQiCMS (AnQiCMS) is an efficient content management system that fully considers these details and provides simple and powerful tools to help us achieve these goals.

Today, let's talk about how to easily replace a specific keyword with another one in the AnQiCMS string and display it on your website page.

Understand the core tool for string replacement:replaceFilter

In the AnQiCMS template system, we have a namedreplaceThe powerful filter. This filter can help us quickly and easily implement string replacement operations.It's like a 'magic scissors' for text, which can accurately find the words you want to replace and change them to new content.

UsereplaceThe filter is very intuitive. Its basic syntax is:

{{ 你的字符串 | replace:"旧词,新词" }}

Here你的字符串Any text content you want to process, such as article titles, descriptions, or even custom field values.旧词It is the keyword you want to replace, and新词Then you want to replace the new content. Both are separated by an English comma,separated.

For a simple example, if you have a string like “Welcome to AnQi CMS”, and you want to replace “AnQi” with “AnQi”, the code would be like this:

{{"欢迎使用安企CMS"|replace:"安企,AnQi"}}

On the page, it will display as "Welcome to AnQiCMS". Isn't it very convenient?

Practical scenarios and code examples

Understood the basic usage, let's see in the actual website operation,replaceWhat problems can the filter help us solve:

1. Replace specific words in the article title or description

Assuming there is an article on your website about 'Free Website Building', but due to brand strategy adjustments, it is necessary to change all instances of 'Free Website Building' in the title or description to 'Efficient Website Building'.

First, you need to use AnQiCMS'sarchiveListorarchiveDetailtags to get the article data, and thenreplaceapply the filter to the title or description field:

{# 假设这里获取到了文章列表中的每一篇文章 item #}
{% archiveList archives with type="list" limit="5" %}
    {% for item in archives %}
        <h3>
            {{ item.Title | replace:"免费建站,高效建站" }}
        </h3>
        <p>
            {{ item.Description | replace:"免费建站,高效建站" }}
        </p>
    {% endfor %}
{% endarchiveList %}

This will automatically update the title and description displayed on the front end even if the content in the background is not modified, to 'Efficient Website Building.'

2. Handle replacements for content containing HTML.

When you need to replace the content of the article text (usually containing HTML tags), you need to pay special attention. AnQiCMS, for security reasons, defaults to escaping the template output, which means that like<p>Such labels may be displayed as&lt;p&gt;To ensure that the rendered HTML content is correct, we need to use in conjunction withsafefilter.

safeThe filter will inform AnQiCMS that this part of the content is safe, does not require escaping, and can be output directly as HTML.

{# 假设获取到了一篇文章详情的Content字段 #}
{% archiveDetail articleContent with name="Content" %}
    <div class="article-body">
        {{ articleContent | replace:"旧内容,新内容" | safe }}
    </div>
{% endarchiveDetail %}

Remember to usesafeThe filter means you need to ensure that the replaced content is reliable and harmless to prevent potential security risks (such as XSS attacks).

3. Combine variable assignment for multi-step operations

In more complex scenarios, you may need to perform multiple steps, such as replacing a word first, then truncating the result, or storing the result for use in multiple places later. At this point,setthe tag comes into play.setThe tag allows you to define a temporary variable in the template.

{% set original_text = "这是一篇关于免费建站系统AnQiCMS的文章,AnQiCMS是您的好选择。" %}
{% set replaced_text = original_text | replace:"免费建站,高效建站" %}
{% set final_output = replaced_text | truncatechars:30 %} {# 再截取前30个字符 #}

<p>{{ final_output }}</p>

This code will first replace "Free Website" with "Efficient Website", then truncate the result to 30 characters (including an ellipsis), and finally display the truncated text on the page.

Attention points when applying the replacement function

While usingreplaceWhen using the filter, there are several points to note:

  • Exact match:replaceThe filter performs an exact string match replacement. This means it does not recognize regular expressions and does not perform fuzzy matching. The one you provided旧词Must match the content of the target string to be replaced.
  • Empty string replacementIf:旧词It is empty,replaceThe filter will insert at the beginning of the original string and after each UTF-8 character sequence.新词If新词If left empty, it will be removed from the string旧词.
  • safeUse of filtersWhen you are replacing content involving HTML structure, be sure to usesafeFilter. But at the same time, please ensure that both the source and the target of the replacement are safe, to avoid introducing malicious code.
  • Front-end and back-end differentiation: AnQiCMS backend also provides the 'Site-wide Content Replacement' feature (under 'Content Management' -> 'Document Keyword Replacement'), which is a powerful tool for batch modifying database content. We are discussingreplaceThe filter is inFront-end template levelReplace in real time display, will not modify the original content in your database. These two methods have different focuses, please choose according to your actual needs.

Summary

AnQiCMS'replaceThe filter is a simple yet powerful template tool that allows you to flexibly control the display of text content on the website without modifying the original data in the background.In order to achieve brand uniformity, SEO optimization, or temporary adjustments, mastering this skill can greatly enhance your operational efficiency.I hope this article can help you better utilize AnQiCMS to create a more flexible and expressive website!


Frequently Asked Questions (FAQ)

1.replaceWill the filter modify the original article content on my website's backend?No.replaceThe filter is onlyin the frontend page renderingPerform a string replacement operation, it will not make any modifications to the original content in your website database.If you need to batch modify the content of the database, you can go to the 'Content Management' module of the AnQiCMS backend, find the 'Document Keyword Replacement' feature.

2. If I want to replace a lot of words, or the replacement rules are very complex,replaceDoes the filter still apply? replaceThe filter is suitable for relatively simple, precise string replacement. If your replacement needs involve a large number of different keyword pairs, or require pattern matching replacement based on complex logic such as regular expressions, then using a singlereplaceThe filter may become cumbersome. In this case, you may need to consider processing some complex replacement logic through the "document keyword replacement" feature in the background before publishing the content, or combine it with other custom development methods to achieve it.

3.replaceThe filter can be used to modify the image link (srcattribute) or image description (altattribute)?It can be. As long as the image link or image description is output as a string variable in the template, you can apply itreplacefilter. For example, if you useitem.LogoOutput the image URL, you can replace it like this:

<img src="{{ item.Logo | replace:"http://旧域名,https://新域名" }}" alt="{{ item.Title | replace:"旧描述词,新描述词" }}">

Remember to ensure the correct format of the new and old links when replacing the URL.