What special characters are the `escape` and `escapejs` filters used to escape in the AnQiCMS template?

Calendar 👁️ 80

In AnQiCMS template development, to ensure the correct display of content and website security, we often use some built-in filters to handle special characters. Among them,escapeandescapejsFilters are two very important tools, each serving different scenarios, and they also have different types of special characters to escape.


escapeFilter: The guardian of HTML safe escaping.

escapeThe filter is mainly used to escape special characters that may be incorrectly parsed by the browser as HTML code, thus preventing security vulnerabilities such as cross-site scripting attacks (XSS) and ensuring that the content is displayed as plain text as expected.

In AnQiCMS templates,escapeThe filter will mainly target the following five core HTML special characters for escaping:

  • <(Less than sign): will be escaped as&lt;If it is not escaped, the browser may interpret it as the start of an HTML tag.
  • >(Greater than sign): will be escaped as&gt;Similarly, it may also be interpreted as the end of an HTML tag.
  • &(ampersand): will be escaped as&amp;Because the ampersand is the starting symbol of the HTML entity reference, not escaping it may cause the content after it to be incorrectly parsed as an HTML entity.
  • "(double quotes): will be escaped as&quot;. When using double quotes in HTML attribute values, if they are not escaped, the attribute value may end prematurely, posing a security risk.
  • '(single quote): will be escaped as&#39;In HTML attribute values when using single quotes (or in JavaScript strings), if not escaped, the string may end prematurely, causing an issue.

It is noteworthy that AnQiCMS's template engine is default enabled for automatic escaping. This means that usually, you even if you do not explicitly useescapeThe filter automatically escapes the special characters contained in the template output. This is an important security feature intended to protect websites from XSS attacks by default.

However, in certain specific scenarios, you may need to intervene manually, such as when you go through{{ variable|safe }}The filter has closed the automatic escaping of a specific variable, but then wants to re-escape a part of the content in HTML; or when passing through{% autoescape off %}The command has disabled the automatic escaping of the entire code block, and it needs to re-enable escaping for specific variables when,escapeThe filter is particularly important.

For example, if you have a variableuserInputContains<script>alert('xss');</script>such content is to be displayed as text on the page rather than executed as a script:

{# 默认情况下,AnQiCMS会自动转义,所以下面的输出是安全的 #}
<p>{{ userInput }}</p>

{# 如果您显式关闭了自动转义,但又想转义特定部分,可以这样使用 #}
{% autoescape off %}
    <p>{{ unsafeHtmlContent|escape }}</p>
{% endautoescape %}

In the above example,|escapeEnsured that special characters in the content are converted to HTML entities, thus displaying them safely as plain text in the browser.


escapejsFilter: Character purifier in the JavaScript environment

AndescapejsThe filter serves different scenarios: It focuses on preparing strings for the JavaScript environment. When you need to output backend data as part of JavaScript code to the front end,escapejsEffectively prevent JavaScript syntax errors or injection vulnerabilities caused by special characters.

withescapePrimarily for escaping HTML special characters differently.escapejsThe escape rules are more strict and comprehensive to meet the requirements of JavaScript syntax. It will convert all characters except letters (a-zA-Z), numbers (0-9), spaces, and slashes (/) into Unicode escape sequences (\uxxxxThe form of...

This means:

  • Carriage return and newline charactersFor example\nWill be escaped to\u000A,\rWill be escaped to\u000D.
  • Quotation marksSingle quote :'Will be escaped to\u0027Comma double quotes"Will be escaped to\u0022.
  • backslash:\Will be escaped to\u005C.
  • other special symbolsFor example!/@/#/$/%and various non-ASCII characters (such as Chinese) will be escaped as\uxxxxforms, to ensure they are not misunderstood or corrupted in JavaScript string literals.

For example, when you need to safely embed a variable containing complex text (possibly with quotes, new lines, or even HTML tags) into a JavaScript string:

<script>
    var message = "{{ backendMessage|escapejs|safe }}";
    alert(message);
</script>

In this example,backendMessageThe content of the variable will first pass throughescapejsProcessed. IfbackendMessageIsHello, "World"!\nThis is a test.Then, it will pass throughescapejsIt may become afterHello, \u0022World\u0022!\u000AThis is a test..|safeIt is necessary here because it tells the template engine:escapejsThe content has been processed into a JavaScript-safe string that can be output directly, without the need for default HTML escaping (otherwise, HTML escaping may escape again)\Symbol, causing JavaScript parsing to fail).


Summary: Choose the appropriate tool.

In short,escapeandescapejsAre two different but equally important escaping mechanisms in the AnQiCMS template, each serving HTML and JavaScript in different context environments.

  • escapeFilterIt is mainly used for HTML text output, escaping< > & " 'To prevent XSS and HTML structure damage. In AnQiCMS, due to default automatic escaping, it is more explicitly used under specific requirements (such as re-enabling after disabling automatic escaping).
  • escapejsFilter: It is used for JavaScript string output, escaping most non-letter, non-numeric, non-space, and slash characters into Unicode sequences to ensure JavaScript syntax correctness and prevent JS injection.

Correctly understanding and using them can help us build secure and robust websites, avoiding page rendering errors or potential security vulnerabilities caused by special characters.


Frequently Asked Questions (FAQ)

Q1: Why am I not being used?escapeFilter, but the HTML tags on the page are still escaped?

A1:The AnQiCMS template engine is enabled by default to escape automatically. This means that for website security, all inputs through{{ 变量 }}The content of the output form, if it contains HTML special characters (such as</>/&The characters (such as &amp;), will be automatically converted to HTML entities to prevent cross-site scripting attacks (XSS). Therefore, you usually do not need to explicitly useescapeThe filter, because the system has already done this work for you.

Q2: Can I use the filter directly?escapeTo escape JavaScript code?

A2:No.escapeThe filter is mainly aimed at escaping special characters in the HTML environment, and the character set and method of escaping are different from the requirements of the JavaScript environment. If theescapeUsed in JavaScript code, may cause JavaScript syntax errors or fail to achieve the expected security effects. Please use specifically designed for JavaScript.escapejsA filter is used to escape string data that needs to be used in JavaScript.

Q3: How can I ensure that a piece of content is safe HTML code and that it is parsed as HTML directly on the page instead of being displayed as plain text?

A3:In this case, you can use|safethe filter. For example{{ trustedHtmlContent|safe }}.|safeThe filter informs the template engine that the content of this variable has been reviewed and trusted, and can be safely output as raw HTML without automatic escaping. However, please use it with caution.|safeEnsure that the content you output is indeed safe, otherwise it may introduce XSS vulnerabilities.

Related articles

How to safely output HTML code in the AnQiCMS template to prevent escaping?

In website operation, we often encounter situations where we need to output content containing HTML code.For example, images, links in the main text, or custom style layouts, etc.When you output this content in an AnQiCMS template, you may find that it is not displayed as interactive elements as expected, but rather displayed in the original HTML code form, for example, `<p>This is a paragraph</p>` becomes `&lt;p&gt;This is a paragraph&lt;/p&gt;`.

2025-11-08

How does AnQiCMS's Markdown editor handle special characters and formatting?

AnQiCMS provides a powerful Markdown editor that not only simplifies content creation but also allows for flexible handling of special characters and formats to meet the needs of different content displays.For users, understanding these processing methods can better utilize the editor's potential to output high-quality page content. ### Enable Markdown Editor Firstly, to use the Markdown editor, you need to make simple settings in the Anqi CMS backend.

2025-11-08

`trimLeft` and `trimRight` filters are used to remove which parts of the string in AnQiCMS templates??

In AnQi CMS template development, we often need to make detailed control and adjustment of the content displayed on the page.The filter is a set of powerful tools provided by the Anqi CMS template engine that helps us easily modify the output format and content of variables.Today, we will focus on the `trimLeft` and `trimRight` filters, which play a crucial role in handling excess content at the beginning and end of strings.In order to better understand them, we will also briefly mention their 'sibling' filter `trim`. Understand

2025-11-08

How to remove extra spaces or specific characters from the beginning and end of a string in AnQiCMS template?

In AnQiCMS template development, fine-grained string processing is a key factor in improving the quality of website content display.We often encounter such a situation: when data is read from the database, user submissions, or text imported from external sources, the beginning or end may carry spaces that we do not want, or even specific punctuation marks or prefix/suffix characters.These extra characters not only affect the visual cleanliness of the page, but may also cause unnecessary trouble to front-end layout, data validation, and even search engine optimization (SEO).AnQiCMS uses similar

2025-11-08

How can keyword library management in AnQiCMS's SEO tool help optimize website content?

In the increasingly fierce online competition, optimizing website content is the key to attracting and retaining users.For operators who want to stand out in search engines and continuously obtain high-quality traffic, a set of efficient SEO tools is undoubtedly a powerful assistant.AnQiCMS as an enterprise-level content management system provides many practical functions in SEO, among which keyword library management is the core tool for us to optimize website content and improve search engine performance. Imagine your website as a library, and keywords are like indexes guiding readers to the books you provide.

2025-11-08

How to add and manage multiple Tag tags in AnQiCMS?

In a content management system, effectively organizing and presenting information is the key to improving user experience and search engine performance.AnQiCMS provides a flexible Tag feature, which allows for more refined categorization of content, making it easier for users to quickly find content of interest and also provides strong support for website SEO optimization.This article will provide a detailed introduction on how to add and manage multiple Tag tags in AnQiCMS, and discuss its practical value in content operation.

2025-11-08

How to call the Tag list of the specified document in AnQiCMS template?

In AnQiCMS, tagging content (Tag) is an effective way to enhance content organization and user experience.These tags not only help search engines better understand the page theme, but also guide users to discover more related content.When you need to display the Tag list associated with a specific document in a template, AnQiCMS provides an intuitive and powerful `tagList` tag to make this operation very simple.

2025-11-08

How to use the `tagDetail` tag to get the detailed information of a Tag, such as description and link?

In AnQi CMS, tags (Tag) are an important tool for organizing content, improving SEO, and enhancing user experience.Sometimes, we need not only to list tags, but also to display detailed information about a specific tag on the page, such as its description, link, and even Logo.At this moment, the `tagDetail` tag comes into play, helping us easily obtain this data.

2025-11-08