How to safely output content containing HTML tags in a template and prevent them from being escaped by the browser?

Calendar 81

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,

Related articles

How to implement multi-condition filtering on a product list or article list page and display the filtered results?

In a content management system, providing users with flexible multi-condition filtering functions is a key factor in improving website usability and user experience.Whether it is an e-commerce website product list or a content portal article classification page, users hope to quickly locate the content they are interested in.AnQiCMS (AnQiCMS) with its powerful content model and template tag system allows you to easily meet this requirement and intuitively display the filtered results. ### 1.Establishing the foundation: defining content models and custom fields All filtering functions rely on data.

2025-11-08

How to display custom additional field content on the detail page?

One of the core strengths of AnQiCMS is its flexible content model feature.It allows us to add various unique custom fields to content based on different business scenarios, such as products, services, events, etc.These custom fields greatly enrich the expression of content, making our website content more professional and meet the needs.But with these additional fields, how can they be presented elegantly on the front-end detail page?

2025-11-08

How can AnQi CMS automatically replace keywords to display article or product content?

In content operations, we often need to ensure that specific keywords in articles or product descriptions are consistent, even automatically associated with related pages, which is crucial for SEO optimization and improving user experience.But manually modifying one by one takes time and is prone to errors, especially when the content of the website is massive, it is also a huge challenge.Anqi CMS knows this, and therefore provides us with a very practical feature, that is, the automatic replacement and display of keywords in articles or product content.This feature can intelligently identify the keywords or phrases you preset and automatically replace them with the specified text or link

2025-11-08

How to determine whether the current item is the first or last in a looped article list so that special styles can be displayed?

In website content management, it is often encountered that there is a need: we hope that the first or last element of the article list, product list, or other data list can have special styles, such as the first article title being particularly prominent, or the last product detail not having a bottom separator line.This not only helps to highlight the key points, but also makes the visual effect of the page more hierarchical.AnQiCMS (AnQiCMS) powerful template engine provides us with a simple and efficient way to meet these customization needs.In Anqi CMS template system, we usually use `{% for ...

2025-11-08

How to extract a part of a long string or HTML content and display an ellipsis at the end?

In website content operation, we often encounter such situations: the article list page needs to display the summary of the content, the product detail page needs to show a brief introduction, or in some special modules, we need to extract a part of the long text or content containing HTML tags, and add "..." at the end to prompt the user that the content is not complete.This not only effectively saves page space and keeps the layout neat, but also improves the reading experience and attracts users to click to view the full content.To achieve such a function, if it were to be manually截取 each time, it would undoubtedly consume a lot of time and effort.Fortunately

2025-11-08

How to format user input plain text content (including newline characters) into HTML paragraphs and newline characters for display?

In website content management, we often encounter such needs: when users input a block of plain text content in the background, it often contains some natural paragraphs and line breaks. We hope that these paragraphs and line breaks are rendered correctly on the website front-end as HTML paragraph tags (`<p>`) and line break tags (`<br/>`), rather than being compressed into a blob or ignored by the browser.AnQi CMS provides a very convenient and powerful template filter to solve this problem, allowing plain text content to be presented elegantly on the web.

2025-11-08

How to convert timestamp data stored in the background into a readable date and time format for display?

When managing website content in Anqi CMS, we often encounter situations where we need to display dates and times.However, the time information stored in the background database is usually in the form of timestamps, which is very efficient for machine processing, but difficult for users to read directly.For example, you might see a string like `1609470335`, which represents a specific moment, but we want it to be displayed in a more friendly format like "2021 January 1 at 12:25:35".fortunately

2025-11-08

How to concatenate the elements of an array into a string separated by a specified delimiter for display?

When managing and displaying content in Anqi CMS, we often encounter situations where we need to merge a group of related information into a coherent text.For example, a product may have many characteristics, and we hope to display the list of these characteristics uniformly with commas or slashes.Or perhaps, an article is associated with multiple keyword tags, and we want to summarize these tags into a single line of text.At this time, the powerful template filter of Anqi CMS can be put to good use, especially the `join` filter, which can help us easily achieve this goal.### Understand the `join` filter

2025-11-08