How to replace a specific keyword with another in AnQiCMS template?

Calendar 👁️ 67

In the flexible template system of AnQiCMS, dynamic content processing is an indispensable part of daily operation.Sometimes, we may need to replace a specific keyword in a string when displaying content, such as displaying a unified brand name consistently, or adjusting the presentation of certain text without modifying the original data.AnQiCMS template engine provides a simple and efficient method to complete this task, among whichreplaceThe filter is our powerful assistant.

UnderstandingreplaceFilter

replaceThe filter is a practical tool in AnQiCMS template language, which allows you to find an 'old keyword' in a string and replace it with a 'new keyword'.This process is entirely performed during template rendering, it does not touch the original data in the database, thus providing you with great flexibility to make various adjustments to the display layers without affecting the content source.

Its basic usage is very intuitive, you can input the string that needs to be processed and then pass it through the pipe|InvokereplaceFilter, and specify the "old keyword" and "new keyword" in a comma-separated manner.

For example, if you have a variable named文章标题The variable contains “Welcome to AnQiCMS”, and you want to replace it with a more brand-sensitive “AnQiCMS”, you can write the template code like this:

{{ 文章标题|replace:"安企CMS,AnQiCMS" }}

After such processing, the content displayed on the page will become "Welcome to AnQiCMS".

replaceThe filter has some special behaviors to note. If the old keyword is set to empty, it will match at the beginning of the string and after each UTF-8 character sequence, which is usually used to insert content between characters.And if the new keyword is set to empty, then the old keyword will be removed.For example, if you want to remove “AnQiCMS” and leave out “AnQi”, you can write it like this:{{ "安企CMS"|replace:"安企," }}The result will be "CMS".

Actual application scenarios and examples

In daily website operations,replaceFilters can be applied to various scenarios:

  1. Standardize brand or term names:When your company name, product name, or industry terminology changes over different periods or needs to be unified in a specific style on a particular page, this filter becomes particularly important. Assuming your article detail page mentions 'AnQi Content Management System', you want to display it as 'AnQiCMS'.

    <p>{{ archive.Description|replace:"安企内容管理系统,AnQiCMS" }}</p>
    
  2. Adjust the display style of URLs or links:Sometimes, the URL you get from the backend may contain the completehttp://orhttps://Prefix, and you want to display only the domain part on the page.

    <a href="{{ item.Link }}">{{ item.Link|replace:"https://,"|replace:"http://," }}</a>
    

    Here, we used it twice in a row.replaceFilter, removed first.https://Then removed again.http://To ensure that any protocol can be displayed uniformly.

  3. Format the separators in the content:If the content output of a field is a date string, for example2023-10-26It shows as you wish2023/10/26,replaceThe filter can help you quickly convert

    <span>发布日期:{{ stampToDate(item.CreatedTime, "2006-01-02")|replace:"-","/" }}</span>
    

    This example combinesstampToDateThe filter first formats the timestamp into a date string, thenreplaceFilter and replace the separators in it.

  4. Simple content correction on the display level:Although it is more recommended to correct the original content in the background, but for some minor typos or temporary content adjustments that do not affect the core data,replaceThe filter can also provide immediate display corrections.

    <h1>{{ archive.Title|replace:"错别字,正确词" }}</h1>
    

Use with other filters

replaceFilters can be used with other filters to achieve more powerful functionality.

  • Process strings containing HTML:It is very important to use when you need to replace content that includes HTML tags (such as the output of a rich text editor article content)|safefilter.AnQiCMSThe template engine defaults to escaping the output HTML content to prevent XSS attacks. If you directly apply HTML contentreplacewithout adding|safe, the browser may display the HTML tags in your replacement result as plain text.

    <div class="article-content">
        {{ archive.Content|replace:"旧的HTML内容,新的HTML内容"|safe }}
    </div>
    
  • To perform case-insensitive replacement:If the case of the old keyword is uncertain, you can first use|loweror|upperThe filter converts the string to uppercase or lowercase and then replaces it.

    {{ item.Title|lower|replace:"cms,内容管理系统" }}
    

    This will be replaced with 'Content Management System' regardless of whether the original title is 'CMS' or 'cms'.

Important reminder

UsereplaceWhen using a filter, it is necessary to clarify its scope. It is simply to modify the output string during template rendering.It is a modification at the display level.It will not change the original content stored in the database. If you need to make large-scale, permanent content changes, such as updating the brand words of the entire site, then you should use the 'Global Content Replacement' feature provided by AnQiCMS backend (which can be found in the 'Content Management' module), it is a batch operation executed on the backend, directly modifying the content in the database, which is also more SEO-friendly.

Moreover, althoughreplaceThe filter is very convenient, but it also needs to consider potential performance impacts when processing very large strings or using it frequently in loops.Moderate use, combined with backend features, can help you better manage and display website content.


Frequently Asked Questions (FAQ)

1.replaceCan the filter implement batch replacement of content throughout the site?No.replaceThe filter is provided by the AnQiCMS template engineFront-end display layerThe tool, it only temporarily modifies the display of the string when the content is rendered on the page.To implement batch modification of all site content (i.e., directly changing the data in the database), you need to use the "Full Site Content Replacement" function in the AnQiCMS backend.

2. I used it in the templatereplaceFilter, but the front-end page does not change, what could be the reason?This usually has several reasons. First, check if your template syntax is correct, including comma separators, quotes, and pipes|The use. Next, confirm whether the template file you modified is the template file currently being used by the website, and whether the AnQiCMS system cache has been cleared after modification.Sometimes browser cache may also cause you not to see the latest changes, try clearing the browser cache or access in incognito mode.

3.replaceDoes the filter support regular expressions for more complex replacements?AnQiCMS template inreplaceThe filter currently does not support regular expressions. It performs simple string matching replacement.If you need to use regular expressions for advanced matching and replacement and want to modify the original data, you should consider using the 'Document Keyword Replacement' feature in AnQiCMS backend, which supports batch replacement using regular expression rules.

Related articles

What is the role of the `index` filter in processing string searches?

In the AnQiCMS template world, efficiently processing and displaying content is the core.Whether it is to dynamically adjust the page display based on user input or quickly locate key information in complex text, mastering the template function can greatly improve the operation efficiency of your website content.Today, let's delve into a very practical tool for string searching—the `index` filter.### `index` filter: 'Locate Expert' string Imagine you have a long article content or a list with multiple tags

2025-11-08

How to get a specific digit from a number: Advanced usage of the `get_digit` filter in AnQiCMS template?

In AnQiCMS template development, flexible handling and displaying data is the key to enhancing website functionality and user experience.When faced with a sequence of numbers, such as product numbers, order numbers, or some kind of identification code, sometimes we do not need the entire number, but rather a specific digit at a certain position.At this time, the `get_digit` filter has become a very practical tool.It can help us extract the required part from the numbers accurately, providing more possibilities for the dynamic display of templates and logical judgment.

2025-11-08

Template content shows: How does the `truncatewords` filter truncate text by word count?

In the presentation of website content, we often need to condense lengthy text information to meet different layout requirements, such as displaying article summaries on list pages, brief descriptions on product cards, etc.This not only makes the page look neater, but also helps visitors quickly grasp the core information.AnQiCMS provides flexible template filters for this type of need, where the `truncatewords` filter is your powerful assistant for truncating text by word count.### A clever and concise summary, making the content clear at a glance

2025-11-08

How to safely truncate the article content using the `truncatechars_html` filter without destroying the HTML structure for website SEO?

In website operation, we often need to display the concise content of articles in article lists, search results summaries, or social media shares.This concise content should not only attract users' attention, but also ensure that the complex HTML structure behind it is not damaged, in order to avoid affecting the layout and user experience.For search engine optimization (SEO), a clean and effective code structure is crucial. AnQiCMS (AnQiCMS) is an enterprise-level content management system developed based on the Go programming language, deeply understanding the pain points and needs of website operation.It not only provides multi-site management, a flexible content model

2025-11-08

Remove extra spaces or specific characters from a string, which filter should be used first (`cut` or `trim`)?

In the template world of Anqi CMS, we often need to clean and format strings, such as removing extra spaces from user input or dealing with specific symbols mixed in with imported content from external sources.At this point, the `cut` and `trim` filters have become our reliable assistants.Although they can all 'remove characters', their working methods and applicable scenarios are fundamentally different.Understanding the difference between these two can help us handle content more efficiently and accurately, making the website display more professional and tidy.

2025-11-08

`trim`, `trimLeft`, `trimRight` filters specific usage scenarios and differences in AnQiCMS templates?

In AnQiCMS template development, handling and optimizing the display of page content is one of the daily tasks.We often need to process the data obtained from the backend to ensure that it is neat and meets expectations on the frontend.Among them, the cleaning of strings, especially the removal of redundant whitespace characters or specific characters, is a key factor in improving content quality and user experience.The AnQiCMS template system provides several very practical filters: `trim`, `trimLeft`, and `trimRight`.They each have their own unique uses and application scenarios.

2025-11-08

How to format numbers or variables into a specified string format: common applications of the `stringformat` filter?

In the template development of Anqi CMS, we often need to display various data obtained from the background in a specific and beautiful format to website visitors.Whether it is the price of goods, the reading volume of articles, or the balance of users' points, the original presentation of data may not always be ideal.This is when the `stringformat` filter becomes a very useful tool.The `stringformat` filter helps us to format numbers, variables, and even more complex structures according to the predefined string pattern and output them.In short

2025-11-08

How does the `add` filter implement flexible connection of text content?

In the Anqi CMS template world, we often need to dynamically combine different content blocks or data, whether it is the sum of numbers or the concatenation of text.At this time, the `add` filter acts as a flexible bridge, helping us easily achieve content concatenation, making the website display more vivid and personalized. ### Deep Understanding of `add` Filter: The Bridge Between Text and Data The `add` filter is a very practical feature in the Anqi CMS template engine, whose core function is to perform addition of numbers and concatenation of strings.It lies in its intelligent processing style

2025-11-08