How to directly output HTML code without being automatically escaped in AnQiCMS templates?

Calendar 👁️ 68

In AnQiCMS templates, we often need to flexibly control the way content is displayed.You may have encountered a situation where you carefully formatted a piece of content containing HTML tags in the rich text editor on the backend, but when it is output on the front-end page, the tags are displayed as plain text instead of being rendered according to the HTML structure.This is actually a security mechanism that is in operation by default in AnQiCMS and many modern content management systems.

Understanding the automatic escaping mechanism in the template

AnQi CMS is an enterprise-level content management system developed based on the Go language, which has always paid close attention to the security of the website. It defaults to escaping all variables output in templates, which means that things like<Will become&lt;,>Will become&gt;,"Will become&quot;This mechanism is mainly used to prevent cross-site scripting (XSS). Imagine if a malicious user enters a piece of code in the comment box.<script>alert('您的账户被盗!');</script>This code, if the system does not escape it directly outputs, then all users visiting the page may execute this malicious script, causing a serious security problem.

However, in a legal usage scenario, for example, if you input a piece with<strong>/<p>The content of tags, or the need to directly embed some custom HTML fragments (such as third-party statistics code, advertising scripts), automatic escaping will bring inconvenience.In this case, we need to explicitly tell the AnQiCMS template engine that this content is safe, does not require escaping, and can be output directly as HTML code.

AnQiCMS template engine provides two main ways to handle this situation: usingsafeFilters andautoescape.

Method one: utilizesafefilter to directly output HTML

When you want the template engine to trust the single HTML variable you provide and output it as is, without escaping it,safeThe filter is your helpful assistant. It tells the template engine that the value of the variable is "safe" and can be processed as raw HTML code.

For example, you enter a piece of HTML text in the article content field on the backend, we usually call it like this:

{# 假设archive是当前文档对象,其Content字段包含HTML内容 #}
{% archiveDetail articleContent with name="Content" %}
<div>
    <p>以下是文章内容:</p>
    {{ articleContent|safe }}
</div>

Here, {{ articleContent|safe }}of|safeIt is the key. It will indicate that the AnQiCMS template enginearticleContentThe value of the variable should be treated as safe HTML and rendered directly without escaping. If omitted|safe, you might see something similar<p>这是一段<strong>加粗</strong>的文字。</p>Such original strings are displayed on the page, not the rendered effect.

Similarly, if you have some custom HTML code stored in a variable, you can also usesafeFilter:

{% set customHtml = "<h2>这是自定义的标题</h2><button>点击我</button>" %}
<div class="custom-section">
    {{ customHtml|safe }}
</div>

This is particularly important when using AnQiCMS rich text editors (such as document content, category content, etc.), because these editors allow users to input rich content containing HTML, and it is almost always necessary to use it in front-end display.|safeFilter to render correctly.

Method two: useautoescapeTag controls the escaping behavior of code blocks.

If you need to handle multiple HTML segments in a large code block, or want to temporarily disable automatic escaping to embed a whole custom code block, autoescapeThe tag provides more flexible control. It allows you to specify whether all variables and text within a region should be automatically escaped.

autoescapeTags need to be associated withonoroffParameters are used together, and{% endautoescape %}End the scope of its effect.

For example, if you want to embed a complete HTML script or third-party code that you control, and do not want it to be escaped by AnQiCMS, you can do this:

{% autoescape off %}
    <p>以下内容在一个特殊区域,不会被自动转义:</p>
    <div>
        {# 即使是可能包含HTML的变量,在这个区域内也会直接输出 #}
        {% set promoCode = "<script>console.log('推广代码已加载');</script>" %}
        {{ promoCode }}
        <a href="#">这是一个普通的HTML链接</a>
    </div>
    <!-- 这里可以放置任何你确信安全的第三方HTML/JS代码 -->
    <iframe src="https://example.com/embed" width="560" height="315" frameborder="0" allowfullscreen></iframe>
{% endautoescape %}

<p>此标签外的区域会恢复默认的自动转义行为。</p>

In{% autoescape off %}and{% endautoescape %}All content including variable outputs will not be automatically escaped.This is very useful for embedding complex external widgets, ad code, or pre-built HTML template fragments.

If you are in a certainautoescape offarea, and you want a specific variable to be escaped (although this is relatively rare), you can explicitly useautoescape onto re-enable:

{% autoescape off %}
    <p>这个区域大部分内容不转义。</p>
    {% autoescape on %}
        <p>但这个嵌套的区块会强制转义:</p>
        <div>{{ "<strong>强调文字</strong>" }}</div> {# 这里会输出 &lt;strong&gt;强调文字&lt;/strong&gt; #}
    {% endautoescape %}
    <p>继续不转义区域。</p>
{% endautoescape %}

Practical scenarios and **practice

Understand and use correctlysafeFilters andautoescapeTags can greatly enhance your flexibility in AnQiCMS template development.

  1. Rich text editor content:This is the most common scenario. For example, the content field of a document (archive)、Category(category) and single page (page) such asarchive.Content/category.Content/page.Content), usually come from the background rich text editor. This content is almost always needed to be displayed on the front end.|safeFilter to render correctly.
  2. Custom HTML snippet: When you hard code some HTML structure in a template or throughsystem/contactthe configuration information obtained with tags such as, it includes HTML fragments.|safethe filter can also be useful.
  3. Markdown rendered HTML:If you have enabled the Markdown editor in the AnQiCMS backend and the content uses Markdown syntax, processed by AnQiCMS'srenderThe output is also HTML after the filter has been processed. In this case, it is also necessary to use|safeto ensure the correct rendering of HTML, for example{{ myMarkdownContent|render|safe }}.
  4. to embed third-party code:Advertising code, statistical scripts, social sharing buttons, etc., these are usually complete HTML or JavaScript fragments, throughautoescape offThe way to wrap them ensures they work properly.

Safety warning: |safeFilters andautoescape offTags are powerful tools but also a double-edged sword. Please make sure that the HTML content you mark as "safe" is completely trustworthy.Any content from user input, or third-party content that has not been strictly verified, if used|safeorautoescape offThis could lead to XSS vulnerabilities, posing security risks to your website. In uncertain situations, it is best to keep the default automatic escaping behavior to ensure the overall security of the website.

Summary

AnQiCMS template automatic escaping is the default and important security feature, but it is not uncontrollable. When we need to output raw HTML code, for a single variable, we can use|safeFilter; while for a code block, you can use{% autoescape off %}...{% endautoescape %}Label. Properly understanding and applying these mechanisms can make our website content more abundant and also effectively maintain the safety line of our website.


Frequently Asked Questions (FAQ)

1. Why does AnQiCMS automatically escape the HTML code I enter?AnQiCMS defaults to HTML-escaping all output content to enhance website security and effectively prevent cross-site scripting attacks (XSS). It will escape HTML special characters such as<and>Convert to their corresponding HTML entities (&lt;and&gt;), thus preventing the browser from interpreting these characters as actual HTML tags or executing scripts, protecting your website and users from malicious code.

2.|safeFilters and{% autoescape off %}...{% endautoescape %}What are the differences between tags?They are all used to prevent HTML auto-escaping, but with different scopes.|safeFilters are applied to the output of a single variable, for example{{ myVariable|safe }}It only affects the value of the variable. And{% autoescape off %}...{% endautoescape %}The tag affects the entire code block, any output of variables within it will not be escaped. If you only need to handle a few variables,|safethe output of the processed variables will not be escaped. If you only need to handle a few variables,|safeSimpler; if you need to embed a large block of raw HTML or script, `autoescape off

Related articles

How to implement the like function for comments in AnQi CMS?

In website operation, enhancing user interaction is a key factor in maintaining the vitality of the website and increasing user stickiness.The comment section is an important battlefield for users to express their opinions and interact with each other. Adding a like feature would undoubtedly significantly enhance the interactivity and community atmosphere of the content.The Anqi CMS is an efficient, customizable, and feature-rich enterprise-level content management system that provides flexible mechanisms, allowing users to easily add the popular interactive feature of liking comments in the comment section.This article will give a detailed explanation of how to implement the like function for comments in Anqi CMS.

2025-11-08

How to display the document comment list and implement pagination?

When using Anqi CMS to manage website content, the comment function on the document detail page is an important part of interacting with readers.Effectively display these comments and ensure that the page maintains good loading speed and user experience as the number of comments increases, it is necessary to properly handle the display and pagination of the comment list.The Anqi CMS provides very intuitive and powerful template tags, helping us easily achieve this goal.

2025-11-08

How to display the comment form and submit comments in Anqi CMS?

It is crucial to establish an effective communication channel with visitors in website operation, and the message function is one of the key tools to achieve this goal.It can not only help websites collect user feedback and answer questions, but also promote user participation, enhance the interactivity and stickiness of the website.For users using AnQiCMS, the built-in message function provides a convenient and flexible solution, allowing you to easily display and submit message forms without writing complex code.### Overview of AnQi CMS Message Function The AnQi CMS message function is designed to be very user-friendly

2025-11-08

How to debug and view the complete structure and value of variables in the template?

When developing website templates in AnQi CMS, we often need to understand the specific structure of a variable on the page and what data it contains so that we can accurately call its properties.When dealing with complex business logic or unfamiliar template variables, being able to quickly view the complete structure and value of variables is undoubtedly the key to improving development efficiency.The Anqi CMS based on the Django template engine provides a concise and powerful variable debugging method for us.### Core Tool: `dump` Filter An enterprise CMS template provides a `dump` named

2025-11-08

How to safely display HTML content generated by the rich text editor in AnQiCMS templates?

In website operation, we often need to handle content from rich text editors, which usually contains richly formatted HTML code.However, when displaying these HTML contents on a website template, security is the primary consideration.If not properly handled, malicious code (such as XSS attacks) may be injected, thereby damaging the website and users.The AnQi CMS is a highly efficient, customizable, and secure enterprise-level content management system that has fully considered content security issues from the outset.

2025-11-08

What potential security risks should be considered when outputting HTML using the `safe` filter?

In AnQiCMS template development, the `safe` filter is a very useful tool that allows us to directly output some content containing HTML tags to the page, rather than escaping the HTML tags as well.This is crucial for displaying details of articles generated by rich text editors, custom HTML modules, and other scenarios, as it ensures the correct rendering of the style and structure of the content.However, like all powerful tools, the use of the `safe` filter also comes with some potential security risks that should not be overlooked.

2025-11-08

Why does my AnQiCMS template still escape HTML code even though I used `safe`?

When using AnQiCMS for website content creation and template customization

2025-11-08

In AnQiCMS, what is the difference in usage scenarios between the `safe` filter and the `autoescape off` tag?

In AnQiCMS template development, we often encounter the need to display content containing HTML tags.For the security of the website, the AnQiCMS template engine defaults to automatically escaping all output variables.This means that if you directly output a text containing HTML tags such as `<strong>` or `<em>`, these tags will not be parsed as styles by the browser, but will be displayed as raw text.

2025-11-08