In the template development of Anqi CMS, how to balance flexibility and security when handling dynamic content is an important consideration. Among them, the HTML automatic escaping mechanism (autoescapeIt played a crucial role, intended to prevent cross-site scripting (XSS) attacks while allowing us to display native HTML content when needed. Understand and masterautoescapeThe use of tags can make you more proficient in template creation.

Understanding automatic escaping: the first line of defense for security protection.

The template engine of AnQi CMS is enabled by default to escape automatically. This means that when you output variables (such as{{ user_input }})If the variable contains HTML tags or JavaScript code, the system will automatically convert them to safe entity characters instead of rendering them as executable HTML code. For example,“}]<div>{{ untrusted_data }}</div>Ifuntrusted_dataThe value of<script>alert('xss');</script>Then the actual rendering of the page will be<div>&lt;script&gt;alert(&#39;xss&#39;);&lt;/script&gt;</div>.

This default automatic escaping mechanism is like a hidden security guardian, greatly reducing the risk of XSS attacks and protecting the website and its users.It ensures that even if the user inputs malicious scripts, they will not be executed on the page.

When do you need to manually control escaping?

Although automatic escaping is the foundation of security, in certain specific scenarios, you may need to turn it off, or explicitly turn it on:

  1. Display rich text or HTML content input by the administrator: EnglishFor example, article details, product descriptions, and other content are usually edited using a rich text editor, which includes valid HTML tags (such as<strong>/<p>/<img>EnglishIf this content is also escaped, the formatting will be destroyed, only showing plain text and messy HTML entities.In this case, we need to turn off automatic escaping, so that the browser can parse these HTML normally.
  2. Ensure that specific code blocks are forcibly escaped:Occasionally, even in environments where global escaping is disabled, or when you need to perform additional security handling on certain parts of a complex variable, explicit escaping can provide finer-grained control.

autoescapeLabel: Flexibly control escape behavior

AnQi CMS providesautoescapeLabel, allowing you to enable or disable automatic escaping within a code block. The scope of this label's effect is limited to the content it wraps.

  • Enable automatic escaping:{% autoescape on %}When you want to force enable automatic escaping within a certain area, even if the global settings may differ, or to override other possible|safemarkers, you can useonParameter.

    {% autoescape on %}
        <p>这个区域的内容将强制进行自动转义:</p>
        {# 假设 article.title 可能包含未经处理的HTML,这里会确保它被转义 #}
        {{ article.title }}
    {% endautoescape %}
    

    In this mode, any variable output betweenautoescape onandendautoescapewill be HTML-escaped.

  • Turn off automatic escaping:{% autoescape off %}When you determine that the content of a code block is safe HTML and needs to be displayed in its original HTML format, you can useoffthe parameter to turn off automatic escaping.

    {% autoescape off %}
        <p>这里的内容将不会被自动转义:</p>
        {# 假设 article.content 包含了来自富文本编辑器的合法HTML,如 "<strong>重要信息</strong>" #}
        {{ article.content }}
    {% endautoescape %}
    

    In this example,article.contentof<strong>The label will be parsed correctly by the browser instead of being displayed as&lt;strong&gt;.Make sure toarticle.contentis from a trusted source and the content has been verified to prevent potential XSS vulnerabilities.

|safeFilter: Unescaped for individual variables

ExceptautoescapeTags, you can also use|safeFilter to handle the escaping behavior of individual variables. When you add|safeWhen, you explicitly tell the template engine: the content of this variable is safe, please do not escape it as HTML.

{# 假设 post.body 包含了合法的HTML内容 #}
<div>{{ post.body|safe }}</div>

Use|safeThe scene is typically, the rich text content you retrieve from the database, and you are confident that these contents have been strictly filtered and verified, and do not contain malicious code.

|escapeFilter: Explicitly force escaping

With|safeOn the contrary,|escapeThe filter is used to explicitly escape a variable. Since the security CMS is enabled by default, in most cases, directly outputting a variable is equivalent to using it.|escape.

{# 等同于 {{ untrusted_input }} #}
<span>{{ untrusted_input|escape }}</span>

However, in{% autoescape off %}块中,|escape就显得尤为重要,它能让您在不转义的区域内,对特定需要转义的变量进行处理。

{% autoescape off %}
    <p>这个区域整体关闭了自动转义。</p>
    <p>但这里有一个需要强制转义的变量:{{ some_user_comment|escape }}</p>
{% endautoescape %}

**实践与安全建议

  • 保持默认设置:Unless there is a clear reason, try to keep the automatic escaping feature of the safe CMS turned on. This is the safest practice.
  • Use with caution|safeand{% autoescape off %}:These are the switches to turn off the security protection.Only use it when you are one hundred percent sure that the output content is strictly verified and safe HTML.For example, the content generated by the rich text editor should be filtered on the server side before being saved to the database.
  • Principle of source trust:Disable automatic escaping only for sources you completely trust (such as rich text entered by administrators in the background). For user-submitted inputs that may contain malicious content, escaping should always be maintained.

By using flexibilityautoescapeTags and related filters, you can effectively manage the display of HTML content in the Anqi CMS, ensuring the security of the website while meeting complex page display requirements.


Common Questions (FAQ)

Q1: Why does AnQiCMS default to enabling automatic escaping? What are the benefits of doing so? A1:AnQiCMS default enables automatic escaping mainly to enhance website security, especially to prevent cross-site scripting (XSS) attacks.XSS attackers will attempt to inject malicious scripts into web pages. If content is not properly escaped and rendered directly, these scripts may steal user data, tamper with page content, or perform other malicious actions.Automatically escape HTML tags and special characters by converting them into entity characters, so that they are displayed as plain text instead of executable code, thereby greatly reducing this risk.

Q2:|safefilters and{% autoescape off %}What are the differences between tags? Which one should I use? A2:They are all used to close HTML escaping, but the scope is different.

  • |safeFilter:Affects a single variable. You add it to the output expression of a specific variable to tell the template engine that the content of the variable is safe and does not need to be escaped. For example:{{ article.content|safe }}.
  • {% autoescape off %}tagsEnglish: acts on a code block.It will close the automatic escaping of all wrapped content (including all variables within it).|safeEasier; If you want all the content within a larger template area not to be escaped, then{% autoescape off %}more suitable. Whichever one you use, please make sure to ensure the safety of the content.

Q3: If I have a variable that is plain text and has no HTML, do I still need to use|safe? A3:In most cases, if the variable indeed contains plain text (without any HTML tags or special characters), thenIt is not necessaryUse|safe。The default auto-escape mechanism of the AnQi CMS has no visible effect on plain text, it only escapes HTML tags and specific special characters. Using|safeIt will not bring any additional display advantages, but may potentially plant security risks if you accidentally assign HTML content to this variable in the future. It is recommended to use it only when you are explicitly required to output raw HTML.|safe.