In the AnQiCMS template system, the core of our daily content display cannot do without the processing of HTML tags.To ensure the security of the website, AnQiCMS defaults to automatically escaping HTML for variables output in templates.This mechanism effectively prevents the injection of malicious code, such as common cross-site scripting attacks (XSS).However, in some cases, we may need to display rich text content containing HTML tags, and at this point, we need to understand how to flexibly control this automatic escaping function.
Automatic escaping: the first line of defense for website security
The AnQiCMS template is developed based on the Go language, drawing inspiration from the Django template engine syntax, one of its core concepts is security first. When the template engine outputs a variable, for example,{{ some_variable }}ifsome_variablehas a value of<script>alert('xss');</script>The output to the page will be escaped by default<script>alert('xss');</script>. The browser will recognize it as plain text rather than executable script, thus ensuring the security of website access.This is a default behavior that is an important security feature of the system, which greatly reduces the risk of security vulnerabilities caused by inappropriate content output.
autoescapeTag: Regional control of HTML tag escaping
autoescapeThe tag is a powerful tool in the AnQiCMS template used to control HTML automatic escaping. It allows you to specify an area of the template where automatic escaping is enabled (on(Should the automatic escaping be turned off?off). This provides regional flexibility in handling content from different sources.
{% autoescape off %}: Turn off automatic escaping for a specified region.
When you are sure that the content within a template area is trustworthy and needs to be rendered according to its original HTML structure, you can use{% autoescape off %}tags to wrap this area.
For example, assume you have a variableproduct_descriptionIt stores the product description entered in the backend rich text editor in HTML format:
{% autoescape off %}
<div class="product-detail">
<h3>产品描述</h3>
{{ product_description }}
</div>
{% endautoescape %}
In this code block,product_descriptionThe content will not be automatically escaped by AnQiCMS, but will be rendered directly with the included HTML tags. This means that ifproduct_descriptionhas a value of<p><strong>这是产品详情。</strong></p>That means, on the page, 'This is the product details.' will be displayed in bold.
{% autoescape on %}: Explicitly enable automatic escaping (reopen in the closed area)
Although AnQiCMS is enabled by default for automatic escaping, but{% autoescape on %}tags allow you to be in a tag that has already been{% autoescape off %}Close the escaped region and re-enable automatic escaping for a sub-region. This is very useful when outputting mixed content.
Consider the following scenario: In an area where automatic escaping is turned off, you have both HTML content from rich text and unprocessed user input.For safety, you need to ensure that the user input is still escaped.
{% autoescape off %}
<div class="article-content">
{# 这里的内容(如 article.content)不会被自动转义 #}
{{ article.content }}
<div class="user-comments">
<h3>用户评论</h3>
{% for comment in comments %}
<p>
<strong>{{ comment.user_name }}:</strong>
{# 重新开启自动转义,确保用户评论内容安全 #}
{% autoescape on %}
{{ comment.text }}
{% endautoescape %}
</p>
{% endfor %}
</div>
</div>
{% endautoescape %}
In the above example,article.contentIt will not be escaped, butcomment.textEven in a largeautoescape offblock, it will also be because of the nested{% autoescape on %}Labels can regain the protection of automatic escaping.
safeFilter: Fine-grained control for a single variable
exceptautoescapeAnQiCMS also provides this regional control method for tags,safeA filter used toa single variableperform more fine-grained escaping control. When you add|safeIt will explicitly tell the template engine that the value of this variable is 'safe' HTML and does not need to be escaped.
UsesafeFilters are typically used for those cases where you are very sure that the HTML code contained is trustworthy and harmless, such as content obtained from a backend rich text editor.
{% set trusted_html = "<p><em>这段内容是加粗斜体的。</em></p>" %}
{% set user_input = "<script>alert('恶意脚本');</script>" %}
<p>通过 `|safe` 过滤器渲染的信任 HTML:</p>
<div>{{ trusted_html|safe }}</div>
<p>未经 `|safe` 过滤器处理的用户输入(仍会被自动转义):</p>
<div>{{ user_input }}</div>
In the above code,trusted_htmlIt will be directly parsed as HTML, anduser_inputVariables even if they contain scripts will be safely displayed as text due to the default automatic escaping.
Important reminder: safeThe use of filters should be very careful. Once used|safeYou have given up the security protection provided by AnQiCMS. If the content of the variable comes from an untrusted source (such as form data submitted by the user),Absolutely notUse|safeunless you have strictly filtered and sanitized the content on the server side.
escapeFilter: Explicit forced escaping (useful in certain cases)
escapeFilter (can also be abbreviated as)eThe role of ) is to explicitly escape the content in HTML. In the case of AnQiCMS where automatic escaping is enabled by default, it outputs directly{{ variable }}and use{{ variable|escape }}The effect is usually the same because the default mechanism has already completed escaping.
However,escapeFilter is on{% autoescape off %}An element can function within an area. If you are in an area where automatic escaping is turned off, you need to make sure that the content of a specific variable is escaped, you can use|escapefilter.
{% autoescape off %}
<p>在这个区域内,默认不进行自动转义。</p>
{% set user_data = "John Doe & Co. <script>evil()</script>" %}
<p>原始输出:{{ user_data }}</p> {# 不会转义 #}
<p>强制转义后的输出:{{ user_data|escape }}</p> {# 会被转义 #}
{% endautoescape %}
In this example,{{ user_data }}Content containing scripts will be directly output, which may pose a security risk.{{ user_data|escape }}It will escape the special HTML characters within it, ensuring safety.
Practical suggestions
- Keep default automatic escaping:Unless there is a clear and legitimate reason, you should always trust the default automatic escaping mechanism of AnQiCMS. This is the foundation of website security.
- Use with caution.
safeFilter:Use only when the content source is absolutely trustworthy (such as administrators entering in the backend rich text editor)|safeFilter. Avoid marking unverified user-submitted data assafe. - Preferred
|safeSecond choice,autoescape off:When you need to display HTML content, it is preferable to use a filter for individual variables|safeinstead of using{% autoescape off %}Label to enclose large areas. This can more precisely control what content is 'safe' and reduce potential security vulnerabilities. - User input should always be escaped:Any content directly from user input should be considered untrusted. Even in
autoescape offthe area, ensure that it goes through|escapea filter or re-enable.{% autoescape on %}Escape processing unless your backend program has already performed strict whitelist filtering and sanitization.
Understand and apply correctlyautoescapetags as wellsafeandescapeThe filter is an indispensable skill in AnQiCMS template development. It can help you display a wide variety of content flexibly while ensuring website security.
Frequently Asked Questions (FAQ)
- **Q: Why AnQi