In the AnQiCMS template system, our daily content display is inseparable from the handling of HTML tags.To ensure the security of the website, AnQiCMS defaults to automatically escaping variables output in templates.This mechanism effectively prevents the injection of malicious code, such as common cross-site scripting (XSS) attacks.However, in certain scenarios, 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 feature.
Automatic escaping: the first line of defense for website security
AnQiCMS template is developed in Go language, drawing on the syntax of Django template engine, one of its core concepts is security first. When the template engine outputs a variable, for example{{ some_variable }}Ifsome_variableThe value of<script>alert('xss');</script>Then, by default, the output to the page will be the escaped<script>alert('xss');</script>.The browser will recognize it as plain text rather than executable script, thus ensuring the safety of website access.This default behavior is an important security feature of the system, which greatly reduces the risk of security vulnerabilities caused by inappropriate content output.
autoescapeTag: Regional control HTML tag escaping
autoescapeTags are a powerful tool in AnQiCMS templates used to control HTML automatic escaping features. It allows you to specify a certain area of the template to be enabled for automatic escaping (on)or disable automatic escapingoff)。This provides regional flexibility in handling content from different sources.
{% autoescape off %}:disable automatic escaping for the 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 input from the backend rich text editor in HTML format:
{% autoescape off %}
<div class="product-detail">
<h3>产品描述</h3>
{{ product_description }}
</div>
{% endautoescape %}
In this code,product_descriptionThe content will not be automatically escaped by AnQiCMS, but will be rendered directly with the included HTML tags. This means that ifproduct_descriptionThe value of<p><strong>这是产品详情。</strong></p>So the text, "This is the product details." on the page will be displayed in bold.
{% autoescape on %}: Explicitly enable automatic escaping (reopen in the closed area)?
Although AnQiCMS is default enabled for automatic escaping,{% autoescape on %}tags allow you to be in one that has already been{% autoescape off %}Within an unescaped region, re-enable automatic escaping for a sub-region. This is very useful when outputting mixed content.
Consider the following scenario: In an area with automatic escaping turned off, you have both HTML content from rich text and unprocessed user input.For safety, you need to ensure that 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.contentis not escaped, butcomment.texteven in a largeautoescape offblock, it will also be because of the nested{% autoescape on %}Label and regain the protection of automatic escaping.
safeFilter: Fine-grained control for a single variable.
ExceptautoescapeIn addition to this regional control method of labels, AnQiCMS also providessafeFilter, used to performIndividual variablesmore refined escaping control. When you add|safeWhen, it explicitly tells the template engine that the value of this variable is 'safe' HTML and does not need to be escaped.
UsesafeFilters are typically used in situations where you are very sure that the HTML code contained is trusted 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_htmlWould be directly parsed as HTML by the browser,user_inputVariables, even if they contain scripts, would be safely displayed as text due to the default auto-escaping.
Important reminder: safeThe use of the filter should be particularly careful. Once used,|safeYou gave up the security protection provided by AnQiCMS. If the content of the variable comes from an untrusted source (for example, form data submitted directly by the user),must notUse|safeUnless you have strictly filtered and sanitized the content on the server side.
escapeFilter: Explicitly escaping (useful in certain cases)
escapeFilter (can also be abbreviated as)eThe role of ) is to explicitly escape content as HTML. In AnQiCMS, under the default automatic escaping setting, outputting directly{{ variable }}and using{{ variable|escape }}The effect is usually the same, because the default mechanism has already been escaped.
However,escapeFilter is{% autoescape off %}The function can be played in the area. If you are in an area with automatic escaping turned off, you need to ensure 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 }}The script content will be output directly, which may cause security risks.{{ user_data|escape }}It will escape the special HTML characters within, ensuring safety.
Practical Suggestions
- Keep the default automatic escaping: Trust AnQiCMS's default automatic escaping mechanism always unless there is a clear and justified reason. This is the foundation of website security.
- Use with caution
safeFilter:Only use when the content source is absolutely可信(such as administrators inputting in the backend rich text editor)|safeFilter. Avoid marking unverified data submitted by users assafe. - Priority
|safe, Secondary optionautoescape off:When you need to display HTML content, prefer to use a filter for a single variable rather than|safeusing{% autoescape off %}Wrap large areas with tags. This allows for more precise control over what content is "safe", and reduces potential security vulnerabilities. - User input should always be escaped:Any content directly from user input should be considered untrusted. Even in
autoescape offthe area,|escapeensure that it is filtered or re-enabled{% autoescape on %}To be escaped, unless your backend program has already performed strict whitelist filtering and sanitization on these inputs.
Understand and apply correctlyautoescapeTags as wellsafeandescapeFilter, is an indispensable skill in AnQiCMS template development. It can help you display a rich variety of content flexibly while ensuring website security.
Common Questions and Answers (FAQ)
- **Q: Why AnQi