How to search and replace specific keywords in the `replace` filter of the Anqi CMS template?

Calendar 👁️ 70

In the daily content management and template design of AnQi CMS, we often encounter the need to search and replace specific content in strings.Whether it is to unify brand names, filter sensitive words, or adjust the display format of some text, manually modifying a large amount of content is undoubtedly tedious and inefficient. 幸运的是,AnQi CMS提供了一个非常实用的模板过滤器——replaceIt can help us easily implement these string operations.

replaceFilter: Your string processing expert

replaceThe filter is a powerful tool built into the Anqi CMS template engine, its core function is to find all matches of the "old word" in the specified string and replace it with the "new word".This process is completely automated during template rendering, requiring no intervention from you in the background database or manual editing of each article, greatly enhancing the flexibility and efficiency of content operation.

Imagine if your website needs to replace all occurrences of "安企" with "AnQi", or to remove a specific phrase that is no longer in use,replaceThe filter can be put to good use. It allows you to flexibly control the final display effect of the content without touching the original data.

How to usereplaceFilter?

replaceThe syntax of the filter usage is very intuitive and simple. It is usually attached to the variable you want to process and provided in the form of "old word" and "new word" separated by a colon.

The basic syntax format is as follows:

{{ obj|replace:"old,new" }}

Here:

  • obj: Represents the original string variable that you want to perform find and replace operations on. This can be article titles, content descriptions, custom fields, etc., any string type of data.
  • old: Is what you hope to findobjThe specific keyword to be searched and replaced.
  • new: Is the new keyword you use to replaceoldThe new keyword.

Please pay special attention to,oldandnewBe sure to use betweenEnglish comma,It separates.

Let's understand its basic usage with a simple example. Suppose you have a variablesiteNameThe value is “Welcome to AnQi CMS”, now we want to replace “AnQi” with “AnQi”:“

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

afterreplaceThe display result of the page after the filter is processed will be:

欢迎使用AnQiCMS

Flexible application scenarios and practical examples

replaceFilters are not limited to simple one-to-one replacements and can also achieve some more sophisticated string operations

1. Conventional keyword replacement

This isreplaceThe most common usage is to replace a specific word in a string with another. This is very helpful for standardizing terms, updating brand names, or correcting common errors.

Example: Replace the old brand name in the article content with the new brand name.

Assuming the content variable of one of your documents isarticleContentIn which multiple occurrences of "Old Company Name" were found, and now need to be unified to display as "New Company Name":

{# 假设 articleContent 变量内容为 "旧公司名称发布了新产品,旧公司名称市场前景广阔。" #}
{{ articleContent|replace:"旧公司名称,新公司名称" }}

After processing, the displayed content will be:

新公司名称发布了新产品,新公司名称市场前景广阔。

2. Insert content between each character.

When you are going tooldWhen the old keyword is set to an empty string,replaceThe filter will become very interesting. It will insert the specified at the beginning of the original string and after each UTF-8 sequence (i.e., after each character).new(New keyword). This usage is very practical when it is necessary to format text in a special way.

Example: Insert hyphens between each character in the text.-.

If you have a string 'Welcome to Anqi CMS' and you want to add a hyphen between each character, you can do it like this:

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

After processing, the display result on the page will be:

-欢-迎-使-用-安-企-C-M-S-

Please note that this method will also add at the beginning of the stringnew. If you do not want to add at the beginning, you may need to combine other string processing methods (such assliceortrimLeft) to remove the characters at the beginning.

3. Remove specific content from a string

If your goal is to directly remove a keyword from the string without replacing it with something else, then you can simplynew(New keyword) Set to an empty string.

Example: Remove specific adjectives from the article title.

Assuming you have an article title variablearticleTitleAmong them, "Exclusive" is often included, but you hope to remove it in some display scenarios:

{# 假设 articleTitle 变量内容为 "安企CMS(独家)发布全新功能" #}
{{ articleTitle|replace:"(独家)," }}

After processing, the article title will be displayed as:

安企CMS发布全新功能

UsereplaceTip for the filter

  • Case sensitive: replaceThe filter is case sensitive. This means that “CMS” and “cms” are considered different words.If you need case-insensitive replacement, it is usually necessary to preprocess the data when obtaining it (such as converting to uniform case), or to implement it in the background management.
  • Non-destructive operation: replaceThe filter only affects the display effect during template rendering, it will not change the original content stored in your background database.This provides you with secure content display control without worrying about accidental modification of the source data.
  • Chaining usage:If you need to perform multiple different replacement operations on the same string, you can concatenate multiplereplacefilters together, for example:{{ obj|replace:"old1,new1"|replace:"old2,new2" }}.

Frequently Asked Questions (FAQ)

Q1:replaceDoes the filter support regular expressions for more complex matching and replacement?

A1:Safe CMS template'sreplaceThe filter design philosophy is simple and efficient, mainly used for simple string to string replacement.According to the document description, it does not support regular expressions. If you need to use regular expressions for advanced pattern matching and replacement, you may consider preprocessing your content before publishing through backend management functions (such as the 'Document Keyword Replacement' function in document management) or using more powerful server-side scripts.

Q2: I want to replace multiple different keywords, and I need to write many of them.replacefilter?

A2:Yes, if you have multiple unrelated keywords to replace, the most direct method is to use them in a chained manner as mentioned abovereplacea filter. For example:

{{ articleContent|replace:"旧公司名称,新公司名称"|replace:"旧产品系列,新产品系列"|replace:"(已过期)," }}

This ensures that each replacement operation is executed in order, thereby achieving the desired final effect.

Q3: Why did I use in the templatereplaceThe filter is applied, but the content on the page does not change?

A3:If you encounter this situation, you can investigate from the following aspects:

  1. Keyword matching issue:Make sure youoldThe keyword in the parameter matches the original string content exactly, including case, spaces, or special characters.replaceThe filter is an exact match.
  2. Comma separator:Checkoldandnewwhether the correct one has been used betweenEnglish comma,to separate. Chinese commas or other characters will cause the filter to fail to parse correctly.
  3. whether the variable is correct:Confirm the operation you want to perform.objWhether the variable has correctly obtained the expected string content. It can be{{ obj }}output individually to check its original value.
  4. Template cache:Sometimes, even if the template file is modified, the browser or system may have a cache.Try clearing the browser cache or clearing the system cache in the "Update Cache" function of the Anqi CMS backend, and then refreshing the page to see the effect.

Related articles

How does the `repeat` filter output a string repeated a specified number of times?

During the process of website content creation, there are times when we have the need to output a specific string multiple times, such as for visual separation, placeholder content, and quick generation of list items.In the AnQiCMS template system, the `repeat` filter provides a very practical function that can help us complete this task efficiently.This filter, as the name implies, repeats a string according to the number we specify, thus saving the trouble of manual copying and pasting, greatly enhancing the efficiency and flexibility of template writing.###

2025-11-08

How do the `removetags` and `striptags` filters remove specified or all HTML tags when processing HTML content?

In the daily content operation of AnQi CMS, we often encounter situations where we need to handle HTML content.To display plain text summaries in specific scenarios, or to standardize content output and enhance security, removing HTML tags is a common requirement.AnQi CMS provides two very practical template filters: `removetags` and `striptags`. They each have unique purposes and application scenarios, let us delve into how they help us efficiently clean HTML content.###

2025-11-08

How to use the `random` filter in Anqie CMS template to randomly return a character or value from a string or array?

In AnQi CMS template development, sometimes we hope to add a touch of dynamism and surprise to the website content, so that visitors can see different elements each time they refresh the page.This is a very practical tool, the `random` filter.It can help us randomly select one from a set of predefined data to display, whether it is randomly selecting characters from a string or randomly selecting a value from an array (or list), it can be easily achieved.

2025-11-08

How does the `phone2numeric` filter convert letters on a mobile phone's numeric keypad to the corresponding numbers?

In AnQiCMS template development, we often need to handle various data, and sometimes we may encounter some special situations with phone number input and display.For example, some phone numbers include letters (also known as "pretty numbers" or "vanity numbers", such as 1-800-FLOWERS) for ease of memorization or brand promotion.However, when dialing in practice, these letters need to be converted to the numbers on the corresponding number keypad.AnQiCMS provides a very practical built-in filter——`phone2numeric`, which helps us easily complete this conversion

2025-11-08

How to slice a string or array elements within a specified range using the `slice` filter?

The AnQiCMS template engine provides rich filters, giving you great flexibility in displaying content.Among them, the `slice` filter is a very practical tool that can help you accurately extract elements within a specified range of strings or arrays, whether you want to display an article summary, limit the number of images, or handle other data segments, it can be very useful.### The working principle of the `slice` filter The syntax of the `slice` filter is concise and clear: `{{ obj|slice:"from:to" }}`

2025-11-08

How `split` and `make_list` filters split a string into an array by a specified delimiter or character?

In Anqi CMS template development, flexibly handling string data is an indispensable skill for building dynamic pages.Sometimes, we need to split a long string into a data list using a specified character or string as a delimiter (which is what we commonly call an array);At other times, we may need to process each character of the string independently.AnQi CMS provides two very practical filters: `split` and `make_list`, which can help us easily meet these needs.###

2025-11-08

How does the `stringformat` filter customize the formatted output of any variable like Golang's `fmt.Sprintf()`?

In content operation, the way content is presented often determines the first impression and reading experience of users.Sometimes, simple variable output cannot meet our needs for fine-grained data formatting display, such as retaining fixed decimal places for numbers or adding specific text before output.AnQi CMS provides powerful content rendering capabilities for template developers and content operators, and the `stringformat` filter is a key tool for achieving refined output.It is like the `fmt.Sprintf()` function in Go language, which can format the output of any variable according to custom specifications

2025-11-08

How to get the thumbnail version of the image according to the image address using the `thumb` filter in the Anqi CMS template?

In website content management, the effective use of images is crucial for improving user experience and page loading speed.AnQiCMS deeply understands this, providing powerful image processing functions, among which the `thumb` filter is a tool that helps us easily obtain the thumbnail version of images.Why thumbnails are so important?Imagine if all the images on your website loaded in their original high-definition large size, how heavy the page would become!

2025-11-08