During the template development process of AnQiCMS, we often encounter situations where we need to process string content, andreplaceThe filter is one of the very practical tools. It can help us easily replace specific parts of a string.However, in practice, ensuring that this filter works in the way we expect is an indispensable part of debugging the template.

UnderstandingreplaceFilter

AnQiCMS provides a series of powerful template filters, which allow us to perform data transformation on template variables without writing complex logic. Among themreplaceThe core function of the filter, as the name implies, is to replace a certain "old word" with a new word in a string.

Its basic syntax is very intuitive:{{ 变量 | replace:"旧词,新词" }}

For example, if there is a variablesiteNameThe value is"AnQiCMS 是一个内容管理系统"And we want to replace 'Content Management System' with 'CMS', it can be used like this:{{ siteName | replace:"内容管理系统,CMS" }}The result will be:AnQiCMS 是一个CMS

It is also important to understand some special cases:

  • If 'old word' is an empty string(""),replaceThe filter exhibits a special behavior: it inserts the word 'new word' after each UTF-8 character sequence in the original string and at the beginning of the string. For example:{{ "欢迎使用安企CMS" | replace:",-" }}It will output.-欢-迎-使-用-安-企-C-M-S-.
  • If the 'new word' is an empty string(""),replaceThe filter will then directly delete the matched 'old word'. For example:{{ "欢迎使用安企CMS" | replace:"安企," }}It will output.欢迎使用CMS.

VerifyreplaceDoes the filter work as expected

When debugging templates, we have many methods to verifyreplacefilter.

1. The most direct way: output directly on the page

This is the simplest and most commonly used verification method. Apply it to yourreplaceThe variable of the filter is directly output to the HTML page, and then check if the page rendering result meets the expected.

Assuming we have a variablearticleContentAmong them is a text that we suspect may have a brand name written incorrectly, and needs to be replaced:

{# 假设 articleContent 变量的值是 "这是安企CMS的测试文章,安企CMS提供卓越服务。" #}
<p>原始内容:{{ articleContent }}</p>
<p>替换后内容:{{ articleContent | replace:"安企CMS,AnQiCMS" }}</p>

Save the template and refresh the page, and we can immediately see the comparison of content before and after replacement, thereby determining whether the replacement is successful.

2. CombinedsetLabel and conditional judgment (if) for verification

When the replacement logic is complex or needs to be further processed based on the replacement result, direct output may not be enough, we can usesettags to capturereplacethe result of the filter, then useifTags are used for conditional judgment. This helps us verify whether the replacement has achieved a specific effect, such as whether a word has been successfully deleted, or whether a new word has been successfully inserted.

{% set originalText = "这是一篇关于GoLang和Go的文章。" %}
{% set replacedText = originalText | replace:"GoLang,Go" %}

<p>原始文本: {{ originalText }}</p>
<p>替换后文本: {{ replacedText }}</p>

{% if replacedText | contain:"GoLang" %}
    <p>错误:替换后仍然包含 'GoLang'。</p>
{% else %}
    <p>验证成功:'GoLang' 已被成功替换。</p>
{% endif %}

In this way, we can not only see the result of the replacement, but also confirm the accuracy of the replacement through automated judgment.containThe filter (used to determine if a string contains a substring) is very useful here.

3. UsedumpFilter depth probe variable

If the replacement result does not match the expected outcome, especially when dealing with special characters, whitespace, or when the variable type is uncertain,dumpThe filter will become your helpful assistant.dumpThe filter can output the internal structure, type, and value of a variable in detail, helping us understandreplaceWhat is the actual input received by the filter, and how is the result represented at the bottom level.

{% set problemText = "  Hello World  " %}
<p>原始文本(dump):{{ problemText | dump }}</p>

{% set replacedProblemText = problemText | replace:" ","-" %}
<p>替换后文本(dump):{{ replacedProblemText | dump }}</p>

BydumpOutput, we can clearly see whether the spaces in the string are ordinary spaces or other whitespace characters, and how the replacement operation affects the structure of the entire string.

4. Combine replacements for HTML content:safeFilter

If yourreplaceThe filter needs to process strings containing HTML tags, and if you want the replaced content to be parsed as HTML by the browser instead of plain text, then you must usesafeFilter. Otherwise, the browser will display all HTML tags as plain characters.

{% set htmlContent = "<p>原始内容</p><span>需要替换的词</span>" %}
{% set replacedHtml = htmlContent | replace:"需要替换的词,<b>已替换</b>" %}

<h3>不使用 safe 过滤器:</h3>
<div>{{ replacedHtml }}</div> {# 会显示 HTML 标签 #}

<h3>使用 safe 过滤器:</h3>
<div class="result">{{ replacedHtml | safe }}</div> {# 浏览器会解析 HTML #}

When validating, it is necessary to check the plain text output (withoutsafe)and HTML parsing output (withsafe),ensure that the tag structure is replaced correctly and no unexpected HTML disruption is introduced. At the same time, also remind yourself to usesafeThis means we trust the safety of this HTML content, be sure to prevent potential XSS attacks.

Examples of actual application scenarios

  • Unified brand name:Replace all occurrences of "AnQiCMS" in the article with "AnQiCMS".
  • Correct typos:Batch correct a fixed and common typo in the template.
  • Handle sensitive words:Partially replace sensitive words in the content submitted by the user (although it is recommended to handle it on the backend, it can also be used for testing on the frontend).
  • Formatted display: toYYYY-MM-DDIn the formatted date string of-Replace/so that it can be used toYYYY/MM/DDDisplayed in form (although there are dedicated time formatting tags).

By the above method, we can efficiently and accurately verify during the AnQiCMS template debugging process.replaceDoes the filter work as expected, ensuring the correct display of content and the stability of the template.


Frequently Asked Questions (FAQ)

1.replaceDoes the filter support regular expression replacement?AnQiCMS template inreplaceFilternot supportedRegular expression. It performs simple literal string substitution.If you need to replace complex content based on regular expressions, this should usually be implemented in backend logic or through functions like "Full Site Content Replacement" in the AnQiCMS backend, rather than at the template level.

2. Why do I usereplaceReplaced HTML content, but the original tags are displayed on the page instead of the parsed HTML?This is usually because you forgot to add to the variable after the replacement|safeFilter. AnQiCMS (and many modern template engines) to prevent XSS attacks, the default is to escape all output HTML tags.If you want the browser to parse the replaced content as HTML, you must explicitly use{{ 变量 | replace:"旧,新" | safe }}.

3. MyreplaceThe filter did not work, what should be checked?Firstly, check the spelling and capitalization of the 'old word' and 'new word' are accurate.replaceThe filter is case sensitive. Additionally, confirm that the variable being used is indeed a string type and that its content matches the expected "old word" exactly.Finally, check the grammar is correct, for example, whether the comma separators are used correctly, and whether the double quotes are closed.You can use|dumpA filter to view the actual value and type of variables to better locate the problem.