How to ensure safe output of HTML content without escaping in AnQiCMS templates?

Calendar 👁️ 46

As an experienced AnQiCMS website operator, I am well aware of the importance of content security output, while also ensuring the complete presentation of high-quality content.In AnQiCMS template development, dealing with HTML content often encounters a core issue: how to ensure that these HTML contents are rendered as expected and not escaped to plain text by the template engine?This not only involves the display effect of the content, but also concerns the security of the website.

AnQiCMS uses a syntax similar to the Django template engine, one of its core design philosophies is security. This means that when you output variables directly in the template, for example{{ 变量 }}The template engine will default to escaping HTML special characters. For example,<div>Hello</div>Will be escaped to&lt;div&gt;Hello&lt;/div&gt;, the browser will display it as plain text, rather than rendering it as an HTML element.This default automatic escaping mechanism is an important security measure to prevent cross-site scripting attacks (XSS).It effectively prevents malicious users from damaging websites or stealing user data by injecting HTML or JavaScript code.

However, in the actual content operation, we often need to output content that inherently contains valid HTML structure.For example, through the AnQiCMS backend rich text editor, the article content may contain paragraphs, images, links, and other HTML tags.If this content is also escaped, then the front-end display of the website will be problematic, and the user will see a chaotic HTML source code.To solve this problem, AnQiCMS provides a clear way to indicate to the template engine which content is trusted and safe HTML that does not require escaping.

UsesafeThe filter explicitly marks safe HTML.

In the AnQiCMS template, the most commonly used and direct method is to usesafeFilter. When you are sure that the HTML content contained in a variable is safe and needs to be output as is, you can apply it.|safeThe filter informs the template engine that the value of this variable is 'safe' HTML, which can be safely output directly without escaping processing.

For example, on the article detail page, we usually retrieve the main content of the article from the database.This content has been edited by the backend rich text editor and inherently contains HTML tags.At this time, you need to ensure that they can be rendered correctly. You can use it like this|safeFilter:

{# 默认用法,自动获取当前页面文档,并安全输出其内容 #}
<div>文档内容:{% archiveDetail archiveContent with name="Content" %}{{archiveContent|safe}}</div>

{# 对于自定义字段,如果也可能包含HTML,同样可以应用 `|safe` #}
{% archiveDetail myCustomHtmlField with name="MyCustomHtmlField" %}
<div>我的自定义HTML字段:{{myCustomHtmlField|safe}}</div>

Please note,archiveDetailthe tag in processingContentWhen a field is processed, if the background has enabled the Markdown editor and setrender=trueit will first convert Markdown to HTML. At this point,|safeIt is still the key to ensure that the converted HTML is not escaped.

UtilizeautoescapeTag controls block escaping

In addition to using for individual variables:safeIn addition to the filter, AnQiCMS also providesautoescapeThe tag is used to control the automatic escaping behavior of HTML in a specific block of the template.This is very useful when you need to handle multiple variables that may contain HTML within a code block, or when you want to temporarily disable automatic escaping.

autoescapeTags have two states:onandoff.

  • {% autoescape on %}: Explicitly enable HTML auto-escape, even if it is already enabled by default.
  • {% autoescape off %}: Disable HTML auto-escape.

One usageautoescape offAn example of a tag is as follows:

{% autoescape off %}
    <p>以下内容将不会被自动转义:</p>
    <div>
        {{ some_html_variable }}
        {{ another_html_string }}
        {# 这里的 <script> 标签如果来自变量,也不会被转义,需要特别小心 #}
        {{ "<script>alert('Hello from AnQiCMS!');</script>" }}
    </div>
{% endautoescape %}

Use{% autoescape off %}Be extra careful when using tags. It will affect the output of all internal variables, meaning any unsterilized user input that is output within this block may introduce an XSS vulnerability.Therefore, unless you have full trust and control over the sources and security of all the content within this block, it is not recommended to use this label extensively.In most cases, for the use of a specific variable|safeFilters are a more refined and secure approach.

**Consideration of Practice and Safety**

As a website operator, security is always the top priority when outputting HTML content in the AnQiCMS template.

  1. Trust the source of content.: Only for content created or strictly filtered and verified by the AnQiCMS backend rich text editor|safeFilter. This content is usually considered trustworthy.
  2. Never trust user input directly.For any original input content submitted by users, such as comments, messages, or other raw data that has not been processed by the backend, do not use it directly even if you think it is HTML|safeor{% autoescape off %}These contents must be strictly purified and verified by the server-side HTML to ensure that no malicious scripts are included.
  3. Understand the riskEach time use:|safeOr filter.{% autoescape off %}Tags mean that you are taking on the risk that this part of the content may introduce an XSS vulnerability. Always assess and understand these risks.
  4. Review codeRegularly review template code, especially that which uses|safeorautoescape offparts, ensuring their use is reasonable and safe.

By appropriately applying|safefilters and using them cautiously when necessaryautoescapeLabel, you can effectively control the output of HTML content in the AnQiCMS template, ensuring the correct rendering of website content and maintaining the security of the website.


Frequently Asked Questions

Why does the AnQiCMS template default to escaping HTML content?

The AnQiCMS template engine defaults to escaping HTML for website security considerations, the main purpose is to prevent cross-site scripting attacks (XSS). By using>/</&Special characters are escaped to HTML entities, the template engine can ensure that malicious users cannot execute unauthorized operations by injecting HTML or JavaScript code into the input, thereby protecting the website and user safety.

If I need to output containing<script>how to operate the code snippet labeled

In most cases, it is strongly recommended not to output containing directly in the front-end template<script>Tag code snippet, especially when this code may come from user input, as this poses a significant security risk. If under specific scenarios (for example, content is obtained from a completely trusted source and has been strictly verified and sanitized on the backend) it is indeed necessary to output this type of HTML, you can use|safea filter. For example:{{ trusted_script_content|safe }}In practice, it is best to avoid this approach, or encapsulate the script logic in an external JavaScript file and pass data dynamically through the backend instead of directly passing the script code.

|safeFilters and{% autoescape off %}What are the differences between tags?

|safeFilters and{% autoescape off %}Tags are all used to disable HTML escaping in functionality, but their scope and usage scenarios are different.|safeThe filter is applied to a single variable, it only tells the template engine that the value of the current variable is safe and does not need to be escaped. And{% autoescape off %}The tag is a block-level tag that turns off the automatic HTML escaping of all variables inside it until it encounters{% endautoescape %}Thus,|safewhich provides finer control,autoescape offIt affects a larger code block, and a more comprehensive security assessment is needed when used.

Related articles

How to cut, replace, or format strings in AnQiCMS templates?

As an experienced CMS website operation personnel in a safety company, I fully understand the importance of content in attracting and retaining users.A powerful and flexible template system that allows us to accurately present content according to different scenarios and user needs.AnQiCMS with its Django template engine syntax, provides us with rich string processing capabilities, whether it is for slicing, replacing, or formatting, it can be easily realized, thus transforming the original data into captivating web content.### AnQiCMS in template string variable acquisition and basic processing in

2025-11-06

How to define and use macro functions to create reusable code blocks in AnQiCMS templates?

As an experienced security CMS website operation personnel, I am well aware that the template function of the content management system is crucial for improving website operation efficiency and content display quality.AnQiCMS's powerful Django template engine syntax provides us with flexible content presentation capabilities, and the Macro function feature is an essential tool for code reuse, simplifying template structure, and improving development and maintenance efficiency.During the process of content creation and publishing, we often encounter some repetitive code snippets, such as the display format of article lists and the layout of product cards

2025-11-06

How to use the `extends` tag in AnQiCMS templates to achieve template inheritance and content rewriting?

In the daily operation of AnQi CMS, we know that high-quality, well-structured website content is the key to attracting and retaining users.This is not only reflected in the words of the article, but also in the overall user experience and maintenance efficiency of the page.AnQi CMS, with its powerful functionality based on the Django template engine syntax, provides us with an efficient template inheritance mechanism, which is exactly what we are going to delve into today - how to use the `extends` tag to achieve template inheritance and content rewriting.

2025-11-06

How to include other template files in AnQiCMS templates (such as public header/footer)?

In the daily operation of AnQiCMS, efficient content management is not only reflected in the background data processing, but also cannot do without flexible front-end template design.For website operators, extracting common parts (such as navigation bars, footers, sidebars, etc.) and managing them independently, and introducing them to each page in a unified way, is the key to improving work efficiency, maintaining website consistency, and simplifying maintenance.AnQiCMS provides a powerful and intuitive template introduction mechanism, making this process effortless.AnQiCMS's template system is based on Go language and has borrowed from

2025-11-06

How to judge if a variable is empty in AnQiCMS template and set a default value?

As a senior AnQi CMS website operation personnel, I know that handling variables with flexibility and robustness is crucial in template development and content display.Especially when the data source may be uncertain or missing, how to elegantly judge whether a variable is empty and provide a reasonable default value, which directly affects the user experience and the stability of page rendering.The AnQi CMS, with its template engine similar to Django, provides us with powerful and intuitive tools to meet these challenges.

2025-11-06

How to get the thumbnail version of the image in AnQiCMS template?

As an experienced CMS website operation personnel, I am well aware of the importance of high-quality content and excellent user experience.In the visual presentation of a website, images play a core role, and the optimization of images, especially the application of thumbnails, is invaluable for improving page loading speed, enhancing user experience, and improving search engine rankings.The AnQi CMS provides strong and flexible support in this aspect, allowing operation personnel to easily obtain and display thumbnail versions of images in templates.In today's content-driven internet environment, it has become commonplace for web pages to contain a large number of images. However

2025-11-06

How to call the switch link of multi-language sites in AnQiCMS template?

As a senior CMS website operator for an enterprise security company, I know that the multilingual site switching link is crucial for expanding the international market and improving user experience.AnQi CMS provides us with a convenient and efficient solution with its powerful multi-site and multi-language support function.Below, I will elaborate on how to call the multilingual site switch link in the AnQiCMS template.Flexible construction of multi-language site switching function Anqi CMS has fully considered the needs of enterprises and operators in global layout from the beginning of its design, originally supporting multi-site management and multi-language content switching

2025-11-06

How to dynamically display the home page banner list in AnQiCMS template?

As a senior who has been deeply engaged in AnQiCMS content operation for a long time, I know the importance of the homepage banner for the visual appeal and marketing promotion of the website.A well-designed and dynamic Banner list that can quickly attract visitors' attention and effectively convey the latest product, service, or event information.Today, I will demonstrate in detail how to dynamically display the Banner list on the website homepage based on the powerful template function of AnQiCMS.

2025-11-06