In website operation, we often need to display information containing rich formatting and media content, such as carefully edited article details, product introductions, or customized pages. This content often includes HTML tags such as image tags<img>, link tags<a>paragraph tag<p>However, if you directly output this content to a web page, you may find that it is not rendered as expected, but is displayed as plain text, showing the HTML tags, which greatly affects the user experience and the beauty of the page.

This is not a problem with AnQiCMS, but a default security mechanism. To ensure website security and effectively prevent potential risks such as cross-site scripting attacks (XSS), AnQiCMS's template engine defaults to process all through{{变量}}The content output in a way that performs HTML escaping. This means, like<script>The label will be converted to&lt;script&gt;This mechanism prevents the browser from recognizing it as executable code. This is particularly important when handling unreliable content submitted by users

Understand the AnQiCMS template mechanism and default escaping

AnQiCMS uses a syntax similar to the Django template engine, variables are enclosed in double braces{{变量}}Output, while the control logic is through single curly braces and the percentage sign{% 标签 %}Define. When you directly output a variable containing HTML in a template, for example{{archive.Content}}, the system will output the following</>Special characters are converted to their corresponding HTML entities to prevent the browser from executing any malicious code embedded within.

This default escaping behavior enhances security, but for rich text content that we want to render 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 certain output content has been reviewed and confirmed safe by the administrator, and indeed needs to be rendered in HTML format, we can use the AnQiCMS template engine provided by|safefilter.

|safeThe filter's role is very direct: it explicitly informs the template engine that this content is 'safe', 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|safeand it is done:

{{ 你的变量 | safe }}

For example:

On the document details page, we usually need to displayarchivethe object'sContentField, this field contains the main content of the article, which may include images, videos, and other HTML elements. In order for this content to be displayed correctly, we will use:

<div>
    {%- archiveDetail articleContent with name="Content" %}
    {{articleContent|safe}}
</div>

Here, archiveDetailthe tag to get the article'sContentContent, and assign it toarticleContentthe variable. Then,{{articleContent|safe}}These contents are ensured to be correctly parsed as HTML by the browser.

Processing rich text content: Common scenarios and注意事项

|safeFilters are crucial in many scenarios:

  1. General content field (such asContent):In AnQiCMS, like articles (archiveDetail)、Single page(pageDetail), category details (categoryDetail)or label details(tagDetail) and other core content areas (usuallyContentA field often contains HTML structure edited through a rich text editor.This content is usually created and managed by administrators and is considered reliable.Therefore, in these scenarios, application|safeThe filter is a crucial step to ensure correct content rendering.

    {# 示例:单页面内容 #}
    <div>
        {% pageDetail pageContent with name="Content" %}
        {{pageContent|safe}}
    </div>
    
  2. Special handling 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 time, you need to use bothrenderParameters and|safeFilter:

    {# 示例:Markdown 内容渲染为 HTML #}
    <div>
        {% archiveDetail archiveContent with name="Content" render=true %}
        {{archiveContent|safe}}
    </div>
    

    Hererender=trueThe parameter tells the template engine to use Markdown formattedContentField is first converted to HTML, then|safeThe filter ensures that the converted HTML can be output to the page without escaping.

  3. Custom field HTML:Sometimes, we might 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 these custom fields also contain HTML tags, the same should be applied.|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 Be Careful?safe?

Although|safeThe filter can solve the problem of HTML content being escaped, but it also brings potential security risks. Its core lies in the fact that once you use|safeYou should clearly 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 (such as<script>alert('您被黑了');</script>)} and you used|safeOutput, then these malicious scripts will be executed in the browser of the users visiting your website. This is known asCross-Site Scripting (XSS)The attacker may steal user information, tamper with page content, or even hijack user sessions by injecting malicious scripts.

Therefore, when using|safeWhen filtering, the following principles must be followed:

  • Only for content sources you completely trust:For example, content created by website administrators through a rich text editor in the backend is usually considered trustworthy because only authorized administrators can edit.
  • Content that cannot be directly used for user submissions and is not strictly sanitized:Any text field that may be entered by the end user, even if it looks like just a normal comment or message, must 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 HTML rendering under the premise of safety (if there is a need for it).AnQiCMS provides functions such as anti-crawling interference code, content security management, sensitive word filtering, etc., which can help improve content security, but still needs to be cautious when outputting user-generated content on the front end.

Advanced control:autoescapeTag

In addition to using for individual variables:|safeOutside the filter, AnQiCMS also providesautoescapeTags to control the automatic escaping behavior within a module block. It allows you to temporarily turn off or turn on the default HTML escaping in a specific code block.

  • {% autoescape off %}:At this tag to{% endautoescape %}Between, all{{变量}}The 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 should be noted that,|safeThe filter will take precedence over.autoescapeTag. That is, even if in the block, a variable is used.autoescape onIn the block, a variable is used.|safeThe variable will still not be escaped. On the contrary, inautoescape offthe block, use|escapethe filter can force the escape.

Summary

In AnQiCMS template, the key to safely output content containing HTML tags is to use them properly|safeOr filter.autoescapeLabel. This requires us to be vigilant about security risks while achieving the expected display effect. For rich text content maintained by administrators and considered trustworthy, use|safeIt is the standard practice. And for content that may contain user input, additional content security measures must be taken to avoid direct use|safe,