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<If it is not escaped, the browser may interpret it as the start of an HTML tag.>(Greater than sign): will be escaped as>Similarly, it may also be interpreted as the end of an HTML tag.&(ampersand): will be escaped as&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". 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'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 &), 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.