In website operation, the security of output content is crucial.Especially when displaying user-submitted data or information obtained from external sources, without proper handling, websites are vulnerable to threats such as cross-site scripting (XSS).escape/eandescapejsThese three filters are the key tools to ensure output safety.

AnQiCMS template engine takes inspiration from Django in its design, which means that automatic escaping is enabled by default. When you output variables in the template, for example,{{ user_name }}The system will automatically convert special characters in HTML (such as</>/&/"/') to their corresponding HTML entities (such as&lt;/&gt;/&amp;/&quot;/&#39;Thus, it effectively prevents malicious HTML or JavaScript code from being parsed and executed by the browser. This default automatic escaping mechanism is the first line of defense for website security.

HTML Context Safe Escaping:escapeandeFilter

Even with default automatic escaping, we still need to explicitly use it in certain specific scenarios.escapeoreFilter. These two filters are equivalent,eYesescapeabbreviations, their purpose is to force the escaping of HTML special characters in strings.

  • FunctionThey will convert the following five HTML special characters to their corresponding HTML entities:.
    • <Converted to&lt;
    • >Converted to&gt;
    • &Converted to&amp;
    • "Converted to&quot;
    • 'Converted to&#39;
  • [en] Application scenarios:
    1. Express the intention clearlyWhen you want to explicitly express that the variable needs to be HTML escaped, even though it is already escaped by default, using it explicitly can enhance the readability and maintainability of the code.
    2. Local close after automatic escaping recoveryIn some special cases, you may need to use{% autoescape off %}Translate the following JSON array content: ["标签临时关闭某个模板区块的自动转义功能(例如输出一段已知安全的HTML结构)。此时,如果区块内有部分内容仍然需要转义,就可以手动使用"] into English:|escapeor|eA filter to ensure the safe output of this part of the content.
    3. Prevent secondary parsingIn some complex rich text processing workflows, if the data may be parsed multiple times,escapeIt can ensure that special characters are always present in entity form when output to HTML, avoiding unexpected double parsing vulnerabilities.

For example, if you have a variableuser_comment, its value might be<script>alert('xss')</script>恶意评论In the context of HTML, it is used.{{ user_comment|escape }}The output will be&lt;script&gt;alert(&#39;xss&#39;)&lt;/script&gt;恶意评论Browsers will treat it as plain text instead of executing scripts.

Safe escaping in JavaScript context:escapejsFilter

When we need to embed dynamic data from the AnQiCMS template into JavaScript code,escapejsThe filter is specifically designed as a security measure.Directly inserting unprocessed variables into JavaScript code can easily lead to JavaScript injection attacks, such as by inserting malicious code through user input enclosed strings.

  • Function:escapejsThe filter will convert special characters in JavaScript code (including carriage returns, line feeds, various quotes, and slashes, etc.) into\uxxxxThe Unicode escape sequences, to ensure these characters are safely interpreted within JavaScript strings or code blocks. It includes all alphanumeric characters (a-zA-Z), spaces, and forward slashes/Escape all characters except those inside quotes.
  • [en] Application scenarios:
    1. Embed dynamic data into JavaScript stringsWhen you need to use the value of a backend variable as a part of a JavaScript string, for examplevar username = '{{ user_name|escapejs }}';.
    2. Insert dynamic data into HTML event attributesin an HTML tag,onclick/onmouseoverInserting dynamic data in event handling functions, for example,<button onclick="doSomething('{{ item.id|escapejs }}')">点击</button>.
    3. Prevent JavaScript injectionBy escaping all characters that may cause ambiguity into harmless forms,\uxxxxescapejsEnsured that even malicious code**enter, can only be part of a string and cannot be executed by the JavaScript engine.

For example, if a variableproduct_nameThe value of"手机",价格:100The insertion of JavaScript directly may cause syntax errors or injection. Instead,{{ product_name|escapejs }}the output may change to手机\x22,\u4ef7\u683c:100This will be safely parsed as a string in JavaScript.

Disable escaping:safeFilter

The counterpart to the above escaping filter issafeFilter. When you confirm that the content of a variable is completely trusted and includes HTML or JavaScript code that you want the browser to parse and execute directly,|safeDisable automatic escaping.

  • Function:safeThe filter tells the template engine that the value it applies is considered 'safe', and no escaping is needed. It can be output in its original form directly.
  • Risk Alert:Please use with cautionsafeFilter.Only when you can completely control and trust the source of the variable's content should you use it. Once user input or data from other untrusted sources is incorrectly marked assafeThis may lead to serious XSS vulnerabilities. For example,{{ trusted_html_content|safe }}.

Summary

Provided by AnQiCMSescape/eandescapejsThe filter is a powerful guarantee for building a secure website.Understanding and correctly using these filters, combined with AnQiCMS's default automatic escaping mechanism, can greatly reduce the risk of the website being attacked by XSS.escapeoreIn JavaScript context, it usesescapejsFor those very few cases where you really need to output original HTML, please consider carefully.safeFilter.


Common Questions (FAQ)

Q1: AnQiCMS template automatically escapes HTML, do I still need to use it?escapeoreFilter?

A1: In most cases, if you are only outputting variables within HTML tags or text content, the default automatic escaping is sufficient for security, and you do not need to use anything extraescapeoreIf you use automatic escaping explicitly in a template area and there is indeed a variable that needs HTML escaping, then you need to use it manually.{% autoescape off %}If you explicitly turn off automatic escaping and there is indeed a variable that needs HTML escaping, then you need to use it manually.|escapeor|eEnsure its security. Moreover, explicitly using these filters can sometimes improve the readability of the code, clearly expressing the developer's intention for the content security handling.

Q2: I directly output the user's input in an HTML page, usingescapejsis it okay?

A2: No.escapejsFilter is specifically used in the JavaScript code context (such as<script>inside a tag or for HTML elements.on*It is the safety output variable in the event attribute. It escapes the content to be recognized by JavaScript.\uxxxxformat. If it is used in ordinary HTML text content,escapejsThe browser will directly display these\uxxxxEscape characters, not the original text you expect, and cannot provide the correct HTML context escaping. AnQiCMS's default automatic escaping is sufficient in HTML content, or use it when automatic escaping is disabled.escapeore.

Q3: UsesafeWhat are the risks of using a filter? When should I use it?

A3:safeThe filter indicates that the AnQiCMS template engine should not escape the values it applies, and output them in their original form. The main risk this brings is that if the value contains malicious HTML (such as<script>Tags) or JavaScript code, which will be executed directly by the browser, leading to cross-site scripting (XSS) attacks. You should only use it in the following situationssafe: When youOne hundred percent sureThe content of this variable is completely trustworthy, and it indeed contains the legitimate HTML code that you want the browser to parse and render.For example, rich text content processed by the backend, published by administrators, or HTML fragments generated and verified internally by the system.|safeOutput.