In website operation, we often need to display information containing rich formatting and media content, such as carefully edited article details, product introductions, or custom pages. This content often includes HTML tags, such as image tags<img>And link tags<a>Paragraph tag<p>English.However, if you directly output these contents to the webpage, you might find that they are not rendered as expected, but are displayed as plain text with the HTML tags, which greatly affects the user experience and the aesthetic beauty of the page.
This is not a problem with AnQiCMS, but a default security mechanism. In order to ensure the security of the website and effectively prevent potential risks such as cross-site scripting attacks (XSS), AnQiCMS's template engine defaults to process all through{{变量}}The content to be output in the way is translated to HTML. This means, like<script>tags will be converted to<script>Thus, avoid the browser from recognizing it as executable code. This mechanism is especially important when handling untrusted content submitted by users.
Understanding AnQiCMS template mechanism and default escaping
AnQiCMS uses a syntax similar to Django template engine, variables are enclosed in double curly braces{{变量}}Output, while the control logic is through single curly braces and percent signs{% 标签 %}defined. When you directly output a variable containing HTML in the template, for example{{archive.Content}}, the system will process the contents of the </>Convert special characters to their corresponding HTML entities to prevent the browser from executing any malicious code embedded within.
This default escaping behavior improves security, but for rich text content that we want to be rendered normally, we need to explicitly inform the template engine that this content is safe and can be rendered with confidence.
Core Solution:safeFilter
When the system determines that some output content has been reviewed and confirmed as safe by the administrator, and is indeed required to be rendered in HTML format, we can use the template engine provided by AnQiCMS.|safeFilter.
|safeThe function of the filter is very direct: it explicitly informs the template engine that this content is 'safe' and does not require HTML escaping, and can be rendered directly as HTML on the page.
Its usage is very simple, just add it to the variable after which you need to output HTML.|safeas follows:
{{ 你的变量 | safe }}
For example:
On the document details page, we usually need to display.archiveObjects'ContentThis field contains the full text of the article, which may include HTML elements such as images, videos, etc. To display this content correctly, we will use:
<div>
{%- archiveDetail articleContent with name="Content" %}
{{articleContent|safe}}
</div>
Here,archiveDetailobtained theContentcontent and assign it toarticleContentthe variable. Then,{{articleContent|safe}}Then ensure that these contents are correctly parsed as HTML by the browser.
Handling rich text content: common scenarios and precautions
|safeFilters are crucial in many scenarios:
General content field (such as
Content):in AnQiCMS, like articles (archiveDetail)、Single Page(pageDetail), category details(categoryDetail) or tag detail (tagDetail) core content areas (usuallyContentField), often contains HTML structures edited through a rich text editor.This content is usually created and managed by administrators and is considered trustworthy.|safeFilter is a critical step to ensure correct content rendering.{# 示例:单页面内容 #} <div> {% pageDetail pageContent with name="Content" %} {{pageContent|safe}} </div>Special processing of Markdown content:AnQiCMS supports Markdown editor, which means some content may be stored in Markdown format.If you have enabled the Markdown editor in the background and want to render Markdown content as HTML and display it, the process will be slightly more complex because the Markdown content first needs to be converted to HTML and then marked as “safe”.
At this point, you need to use both
renderparameters with|safeFilter:{# 示例:Markdown 内容渲染为 HTML #} <div> {% archiveDetail archiveContent with name="Content" render=true %} {{archiveContent|safe}} </div>Here are the
render=trueThe parameter tells the template engine to convert Markdown format to HTML,Contentthen convert the field to HTML,|safeFilter to ensure that the converted HTML can be output to the page without escaping.HTML in custom fields:Sometimes, we may create custom fields in the content model to store specific HTML snippets, such as product feature descriptions, special marketing text, or text blocks that require special style control. If the content of these custom fields also includes HTML tags, the same application is required
|safeThe filter must be enabled to display correctly.{# 示例:自定义字段 'product_features' 包含 HTML #} <div> <h3>产品特色:</h3> {% archiveDetail productFeatures with name="product_features" %} {{productFeatures|safe}} </div>
Safety and Risk: Why to be cautioussafe?
Although|safeFilter can solve the problem that HTML content is escaped, but it also brings potential security risks. Its core is that once you use|safe,you should explicitly tell the system 'I trust this content, it does not contain malicious code'.
If this 'safe' content is actually injected with malicious scripts by an attacker (for example<script>alert('您被黑了');</script>),and you used|safeoutput, then these malicious scripts will be executed in the browsers of the users visiting your website. This is what is known ascross-site scripting attacks (XSS). The attacker may steal user information, tamper with page content, or even hijack user sessions by injecting malicious scripts.
Therefore, when using|safeWhen using a filter, the following principles must be followed:
- Only used for content sources you completely trust:For example, content created by website administrators through the rich text editor in the background is usually considered trustworthy because only authorized administrators can edit.
- Absolutely cannot be used directly for user submitted content that has not been strictly sanitized (Sanitization):Any text field that can be input by the end user, even if it looks like just a simple comment or message, should never be used directly
|safeOutput.This content must be strictly filtered and sanitized by the backend server, removing all potential malicious tags and attributes, before considering rendering it as HTML under the premise of safety (if there is such a need).AnQiCMS provides functions such as anti-crawling interference code, content security management, sensitive word filtering, which can help improve content security, but still needs to be cautious when outputting user-generated content on the front-end.
Advanced control:autoescapetags
Except for using for a single variable|safeFilter external, AnQiCMS also providesautoescapeLabel to control the automatic escaping behavior within a module block. It allows you to temporarily disable or enable the default HTML escaping in a specific code block.
{% autoescape off %}:At this tag to{% endautoescape %}between, all{{变量}}output will not be HTML escaped, which is equivalent to each variable being automatically prefixed with|safeFilter.{% autoescape on %}:This is the default behavior, all{{变量}}The output will be HTML escaped.
Example:
{% autoescape off %}
<p>这个段落里的 {{ untrusted_html_content }} 将不会被转义。</p>
{% endautoescape %}
{% autoescape on %}
<p>这个段落里的 {{ trusted_html_content }} 将会被转义。</p>
{% endautoescape %}
It is worth noting that,|safeThe filter will take precedence over.autoescapetag. That is, even if in the block,autoescape ona variable is used in the block,|safeThe variable will still not be escaped. Conversely, inautoescape offblock, using|escapefilter can force the escape.
Summary
In AnQiCMS template, the key to safely output content containing HTML tags is to use them appropriately|safeFilter orautoescapeLabel. This requires us to be vigilant about security risks while implementing the expected display effect. For trusted rich text content maintained by administrators, use|safeIt is the standard practice. For content that may include user input, additional content security measures must be taken to avoid direct use.|safe,