The `escape` and `escapejs` filters in AnQiCMS are applicable to which HTML/JS escaping scenarios?

Calendar 👁️ 83

In AnQiCMS template development, it is very important to understand and properly use the escaping filter to ensure the security of the website and the correct display of content.The system uses a template engine syntax similar to Django, which means it takes some security measures by default when handling variable output.escapeandescapejsThese two filters, see in which scenarios they can be used separately.

escapeFilter: When you want to display original HTML/XML special characters.

escapeThe main function of the filter is to convert specific HTML/XML special characters in a string to their corresponding HTML entities. It escapes five core characters:<changes to&lt;,>changes to&gt;,&changes to&amp;,"changes to&quot;, as well as'changes to&#39;.

AnQiCMS's template system pays great attention to security, itautomatically escapes all content output from template variables by defaultThis means that when you use it directly{{ variable }}to output a variable, evenvariablecontains<script>the tag, when output to the page it will become&lt;script&gt;which effectively prevents cross-site scripting (XSS) attacks.

Then, since it is escaped by default, when do we need to use it manually?escapeWhat about the filter?

  1. When you need to display the original HTML/XML code textSometimes, your website may need to display a code example, and that code itself is in HTML or XML format.If you directly output, it will be parsed and rendered by the browser.Text formInstead of rendering effects, you may need to use first|safeThe filter explicitly tells the system that this content is “safe” (i.e., you trust that its content will not cause XSS), and then use it again|escapeEscape it as an HTML entity so that the browser will display it as text. For example, you have a variablemyHtmlCodeThe value of"<p>这是一个段落。</p>":

    <!-- 这会渲染出一个段落,因为|safe阻止了默认转义 -->
    <div>{{ myHtmlCode|safe }}</div>
    
    <!-- 这会显示原始的HTML文本,如 <p>这是一个段落。</p> -->
    <div>{{ myHtmlCode|safe|escape }}</div>
    

    Please note, use it first|safeBecause you know explicitlymyHtmlCodeThe HTML is what you want to output, but you also want to display it as text, so you need to bypass the default escaping first.

  2. Explicitly perform double escaping (usually not recommended)As mentioned before, AnQiCMS defaults to automatic escaping. If you add{{ variable }}to such an output again|escapeThis will result in the content being escaped twice. This usually leads to the page displaying incorrectly, for example&lt;p&gt;It may become&amp;lt;p&amp;gt;This is not what we want to see. Therefore, in most cases, please avoid unnecessary|escapeusage.

In addition, AnQiCMS also providesautoescapeThe tag allows you to control the behavior of automatic escaping in specific areas of the template.

  • {% autoescape off %}: All variables within this label block will not be automatically escaped.This is very useful when outputting original HTML is required using third-party libraries or special components, but be sure to ensure that the content you output is absolutely safe, otherwise it will introduce XSS risks.
  • {% autoescape on %}: Explicitly enable automatic escaping, which may be useful in some special cases, such as when a variable is mistakenly marked assafeYou can force it to be escaped.
{# 默认行为,变量会被自动转义 #}
<p>默认转义: {{ dangerous_html }}</p>

{# 关闭自动转义,但务必确保 dangerous_html 是安全的HTML #}
{% autoescape off %}
    <p>关闭转义: {{ dangerous_html }}</p>
{% endautoescape %}

escapejsFilter: When you safely insert data in JavaScript

escapejsA filter is a special escape tool designed for the JavaScript context. Its task is to convert special characters in strings (except letters, numbers, spaces, and slashes/Outside) can be safely recognized as a JavaScript string literal\uXXXXUnicode escape sequence in the form of.

Why do we need a dedicated escape filter for JavaScript? Imagine if you want to assign the value of an AnQiCMS template variable to a JavaScript variable:

<script>
    var userName = "{{ user.name }}";
</script>

Ifuser.namehas a value of'; alert('XSS'); //So the final rendered HTML will be:

<script>
    var userName = ""; alert('XSS'); //";
</script>

This would lead to a serious JavaScript injection vulnerability, where an attacker can execute any JavaScript code on your website.

escapejsThe filter is born to solve such problems.It ensures that all characters that could disrupt the boundaries of a JavaScript string or introduce malicious code are safely encoded.

Use case: Embed data from the server side<script>when the JavaScript variable is inside the tag.As long as you are<script>Inside the tag, the AnQiCMS variable is output to a JavaScript string, array, or object,it mustUseescapejsfilter.

<script>
    var userName = '{{ user.name|escapejs }}';
    var userEmail = "{{ user.email|escapejs }}";
    var message = `欢迎,{{ message_from_backend|escapejs }}`; // 模板字符串中同样适用
</script>

This will escape similar'; alert('XSS'); //content as'\u0027; alert(\u0027XSS\u0027); \/\/Ensure it remains a safe string literal in JavaScript code and is not parsed as executable code.

Core security principle: distinguish between content and code boundaries

In AnQiCMS template development, remember the following core principles, which can help you effectively deal with content escaping and security issues:

  1. It is safe by default.: AnQiCMS template engine defaults to HTML escaping all output. This means that in most cases, you don't need to worry about XSS risks and don't need to manually add|escape.
  2. |safeContent intended for trusted HTMLOnly when you are sure that the HTML content contained in a variable is completely safe and that you want the browser to be able to parse and render it normally, should you use it|safeFilter. For example, the article content stored from the background rich text editor will usually be in HTML format, at this time, use|safeIt allows this content to be displayed correctly. But please ensure that the source of this content is reliable.
  3. |escapejsAlways used in the JavaScript context: As long as you are<script>Insert AnQiCMS variables (especially as part of a string literal), be sure to use|escapejsFilter. This is a critical step to prevent JavaScript injection vulnerabilities.

By understanding and adhering to these principles, you can build high-quality websites that are both beautiful and secure, and can correctly display various content in AnQiCMS.


Frequently Asked Questions (FAQ)

Q1: Why my{{ variable }}The content contains HTML tags, but the HTML entities (such as&lt;p&gt;) are displayed on the page instead of the rendered effect?A1: AnQiCMS template engine defaults to escaping all content output from variables to prevent cross-site scripting (XSS) attacks. If you are sure that these HTML contents are safe and you want them to be parsed and rendered by the browser, you need to use|safeFilter, for example{{ variable|safe }}Please be cautious when using '`

Related articles

How to quickly view the detailed structure and value of complex variables during debugging in AnQiCMS template?

During AnQiCMS template development, we often need to understand what data and structure a variable contains internally, especially when dealing with complex data objects or debugging template issues.Sometimes, direct output of a variable can only yield a simple value or error message, and cannot delve into its detailed composition.At this point, it is particularly important to master some effective methods for viewing the complete structure and value of variables.### The Challenge of AnQiCMS Template Debugging The template syntax of AnQiCMS is versatile, whether it is the system built-in `archive`

2025-11-08

In AnQiCMS template, how to determine if one number can be evenly divided by another to achieve conditional display?

In Anqi CMS template development, we often need to display content based on specific conditions, such as adding a special style to every few elements in a list or inserting separators at specific positions.When this condition is to determine whether a number can be divided by another number, Anqi CMS provides a concise and efficient solution with its powerful template engine.The Anqi CMS template system uses a syntax similar to the Django template engine, which makes it very intuitive in handling such logical judgments.To determine if a number can be evenly divided by another number

2025-11-08

What are the differences and applicable scenarios between the `default` and `default_if_none` filters when the template variable is empty?

In AnQi CMS template design, reasonably handling variables that may be empty is the key to ensuring the integrity and smooth user experience of website content display.When a template variable has no value or is in an 'empty' state, we usually do not want blank or error messages to appear on the page, but rather we would like to display a preset default content.At this time, the `default` and `default_if_none` filters provided by Anqicms come into play.They can all provide default values for variables

2025-11-08

How to format Unix timestamp into a readable date and time format in AnQiCMS template?

In website content management, time information plays a crucial role, whether it is the publication date of articles, update time, or the submission time of comments, the record of time is indispensable.Databases usually store these time data in a concise and efficient format - Unix timestamps.However, for the end user, a string of numbers in a timestamp is not as intuitive and easy to understand as “October 27, 2023 14:30”.

2025-11-08

How to split a line of text content (such as a tag string) into an array of individual words for processing in AnQiCMS?

In the practice of AnQiCMS content management, we often encounter scenarios where it is necessary to split a seemingly simple line of text into smaller, more independent 'words' for fine-grained processing.For example, the document tag (Tag), keyword list, or multiple values separated by a specific symbol in custom fields.The core of this requirement lies in converting a string into an array that can be traversed and manipulated individually.

2025-11-08

How to precisely control the display of floating-point numbers in the AnQiCMS template, such as retaining two decimal places?

In website content operation, the way numbers are presented often affects user experience and the accuracy of information.Especially for floating-point numbers, such as product prices, statistics, and ratings, it is common to require accuracy to several decimal places or rounding according to business needs.AnQiCMS is a powerful template system that provides us with a flexible way to handle these data.Today, let's delve into how to efficiently and accurately control the display of floating-point numbers in the AnQiCMS template.

2025-11-08

How to extract specific number information from a long numeric string in AnQiCMS template?

In website operations, we often encounter scenarios where we need to handle some structured long numeric string.For example, a product code may contain the production date and batch information; an order number may imply regional codes and serial numbers; or may be a unique identifier generated by specific business logic.These long digital strings often carry rich metadata, and we may only need the numerical information at specific positions for display, filtering, or further processing.

2025-11-08

How to find the first occurrence index of a character or substring in the AnQiCMS template?

During the process of displaying website content or template development, we often encounter situations where we need to process specific text, such as checking if a keyword exists or locating the first occurrence of a character or substring.The template engine of AnQiCMS (AnQiCMS) provides a series of powerful filters (Filters) to help us complete these tasks efficiently.Today, let's discuss how to use the `index` filter to accurately find the position index of the first occurrence of a character or substring in the AnQiCMS template.Understand

2025-11-08