How to control the automatic escaping of HTML content with the `autoescape` tag in AnQiCMS templates?

Calendar 👁️ 72

In AnQiCMS template development, for the safety of the website, the system defaults to automatically escaping all HTML content output to the page. This means that when you directly output a variable containing special HTML characters in the template, for example,<script>alert('XSS')</script>,AnQiCMS will convert it to&lt;script&gt;alert(&#39;XSS&#39;)&lt;/script&gt;. This mechanism can effectively prevent cross-site scripting (XSS) attacks and protect the security of the website and user data.

However, in the actual content operation, we sometimes need to display real HTML content, such as the rich text edited in the background, embedded third-party code snippets, or some predefined layout structures. In this case, AnQiCMS provides a flexible mechanism to control the automatic escaping of HTML content, the core of which isautoescapeTags andsafefilter.

Understand the default automatic escaping mechanism

The default behavior of the AnQiCMS template engine (based on Django template syntax in Go language) is security-oriented.No matter what variable you output, if it may contain HTML tags or special characters, the system will automatically convert it to HTML entities.This default behavior runs through the entire template, saving you the trouble of manually escaping characters, and also providing the first level of security.

For example, if you have a variableuser_descriptionIts value is<b>AnQiCMS</b> 是一个 <i>优秀</i> 的内容管理系统output directly in the template{{ user_description }}At this time, you will see&lt;b&gt;AnQiCMS&lt;/b&gt; 是一个 &lt;i&gt;优秀&lt;/i&gt; 的内容管理系统, not bold and italic text.

UseautoescapeTags control the scope of escaping

When you need to turn off or turn on automatic escaping in a piece of template code,autoescapeThe label comes in handy. It allows you to define a clear area where the default escaping behavior can be changed.

To turn off automatic escaping:{% autoescape off %}

If you have a piece of HTML content that you are sure is safe, and you want it to be output as is instead of being escaped as HTML entities, you can use{% autoescape off %}and{% endautoescape %}tags to wrap this content.

{# 默认情况下,这里的内容会被转义 #}
<p>{{ some_raw_html }}</p>

{% autoescape off %}
    {# 在这个区块内,HTML 内容将不会被自动转义 #}
    <div>
        {{ some_trusted_html_from_database }}
        <p>这里可以安全地输出<span>原始的</span>HTML。</p>
    </div>
{% endautoescape %}

{# 这个区块之后,自动转义又会恢复默认开启状态 #}
<p>{{ another_potentially_unsafe_input }}</p>

This method is very suitable for obtaining rich text content from the background that has been strictly reviewed by administrators, or for HTML fragments that you manually write and are confident do not have any security risks.

Enable Auto-escape:{% autoescape on %}

Although AnQiCMS is enabled by default for automatic escaping, if you need to escape the content of a child area within a certain parent area, you can useautoescape offin the area, if it is necessary to escape the content of a sub-area, you can use{% autoescape on %}This can help you finely control the escaping behavior of each part when handling complex or nested template structures.

{% autoescape off %}
    <p>这段内容不会被转义。</p>
    {% autoescape on %}
        {# 即使父级是 off,这个子区域的内容也会被转义 #}
        <p>这里的 {{ user_input_again }} 会被转义。</p>
    {% endautoescape %}
    <p>这段内容依然不会被转义。</p>
{% endautoescape %}

UsesafeThe filter disables escaping of a single variable.

If you only need to disable automatic escaping for a specific variable in the template, not the entire code block, thensafeThe filter is a more concise choice. You just need to add it after the variable.|safeJust do it.

<p>这是来自管理员的富文本内容:{{ article.content|safe }}</p>
<p>这个用户评论:{{ user_comment }}</p> {# 用户评论依然会被转义 #}

Use|safeThis means you declare to the template engine: "I confirm"article.contentThe content of this variable is safe, please output it directly in HTML format without escaping.

escapeFilter: The scenario of forced escaping

withsafeThe opposite of the filter function isescapeA filter that is used to explicitly escape content as HTML. However, since AnQiCMS is automatically escaping by default, in most cases, you can directly output the variable{{ some_content }}The result will be escaped. If you add it again|escapeThe filter, it may cause the content to be escaped twice.

escapeThe more common use of the filter is withautoescape offThe tag is used in conjunction, when you are in an area where automatic escaping is turned off, and you need to force-escape a variable within it, you can use it.

{% autoescape off %}
    <p>这个区块的内容不会被自动转义。</p>
    <p>但是这里的 {{ some_variable_that_needs_escaping|escape }} 会被转义。</p>
{% endautoescape %}

**Consideration of Practice and Safety**

When deciding to turn off automatic escaping or to usesafeBe extremely cautious when filtering. These features should only be applied to HTML content that you completely trust and confirm does not contain malicious code.Any content from user input that is not strictly filtered should always maintain the default automatic escaping to effectively prevent cross-site scripting (XSS) attacks and protect the website and user safety.

In summary, understand and apply flexiblyautoescapeTags andsafeThe filter will help you in AnQiCMS template development, ensuring the rich and diverse display of website content while also building a solid and reliable security defense for the website.


Frequently Asked Questions (FAQ)

Q1:autoescapeTags and|safeWhat are the main differences of the filter?

A1: The main difference lies in the scope.autoescapeThe tag is used to control oneCode block(from{% autoescape off %}to{% endautoescape %}to) the HTML escaping behavior, while|safeThe filter is used to controla single variableThe escape. If you have a large amount of rich text content that needs to be output, usingautoescape offis more suitable; if it's just occasionally one or two variables that need to output raw HTML, then|safethe filter is more convenient.

Q2: When should we useautoescape offor|safeFilter?

A2: Both of these methods should be available to youCompletely trustWhen using the content source. For example, the detailed page content of the article edited by the back-end administrator through the rich text editor, or the HTML structure that you have hard-coded in the template and confirmed to be safe.For any content directly input by the user that has not been strictly filtered, these methods should be avoided to prevent potential XSS attacks.

Q3: Why is it sometimes used|escapeThe filter will escape the content twice?

A3: AnQiCMS's template engine is enabled by default for automatic escaping.This means that when a variable is output, it has already undergone an escape.If you use this variable again on this basis|escapeIf the filter is used, the content will be escaped twice. For example,<The first is escaped into&lt;Maybe escaped again in the second&amp;lt;Thus,|escapeFilters are usually only used after you have{% autoescape off %}Closed within an auto-escaping region, explicit usage is required to manually escape specific variables.

Related articles

How to handle JavaScript code output containing special characters (such as `&lt;script&gt;`) in AnQiCMS?

In website operation, we sometimes need to output custom JavaScript code on the page, which may be to implement specific interactive functions, integrate third-party service scripts (such as statistical codes, advertising codes), or add some dynamic effects to the page.However, when these JavaScript codes themselves contain some special characters, especially HTML tags (such as `<script>`), if not handled correctly, it may cause the page to display abnormally, disable functions, or even bring serious security vulnerabilities.

2025-11-08

What are the differences and usage scenarios between the `escape` filter and the `e` filter in AnQiCMS?

In the development of Anqi CMS templates, we often encounter the need to handle the security of content display, especially when the content may contain user input or be obtained from external sources.It is particularly important to escape special characters at this time to prevent potential cross-site scripting attacks (XSS).AnQi CMS provides the `escape` and `e` filters to help us deal with such issues, they have the same function, and `e` is just an abbreviation alias of `escape`.

2025-11-08

How does AnQiCMS template escape HTML to prevent XSS attacks when displaying user submitted content?

In today's network environment, website security is of great concern to operators, among which cross-site scripting attacks (XSS) are one of the common security threats.XSS attacks inject malicious scripts into web pages, steal user data, alter page content, and even control user sessions.AnQiCMS as a content management system that focuses on security, built a series of powerful HTML escaping mechanisms to effectively prevent such attacks when processing user submitted content and displaying it in templates.

2025-11-08

What are the potential uses of the `safe` filter in AnQiCMS besides displaying HTML?

In AnQi CMS template engine, the default automatic escaping mechanism is an important security feature, which can convert special characters in HTML tags and JS scripts (such as `<`, `>`, `&`, etc.) to corresponding HTML entities, thereby effectively preventing cross-site scripting (XSS) attacks.However, in certain specific content output scenarios, we indeed need to allow the browser to parse and render the HTML or similar HTML code as it is, at which point the `safe` filter becomes crucial.

2025-11-08

How does AnQiCMS automatically convert URLs and email addresses in plain text to clickable HTML links?

In website content creation, we often need to mention URLs and email addresses in articles, descriptions, or comments.If this information is just plain text, users cannot directly click to jump, which undoubtedly affects user experience and the efficiency of information transmission.AnQiCMS as an efficient content management system fully considers this requirement and built-in smart functions can automatically convert URLs and email addresses in plain text to clickable HTML links.

2025-11-08

What are the differences between the `urlize` and `urlizetrunc` filters in converting URLs to links?

In Anqi CMS, when processing text content, we often need to automatically convert the URLs or email addresses contained within into clickable links.This not only improves the user experience, but also helps search engines better understand the content of the page.Therefore, AnQi CMS provides two very practical filters: `urlize` and `urlizetrunc`.Their core function is to intelligently convert URLs and email addresses in text to the HTML `<a>` tag, but there are key differences in specific application scenarios and effects.

2025-11-08

How to convert a newline character (`\n`) in the AnQiCMS template to the HTML `<br/>` tag or `<p>` tag?

In website content operation, we often encounter such situations: when the text content extracted from the database, or the text entered in the background plain text editor, is displayed on the front-end template, the originally clear line breaks become long sentences stacked together.This is because the browser defaults to not parsing newline characters (`\n`) as line breaks in HTML.To solve this problem in the AnQiCMS template, we need to use the powerful template filter function of AnQiCMS to display text content as expected in line.

2025-11-08

What are the differences between the `linebreaks` and `linebreaksbr` filters in handling text line breaks?

In AnQi CMS template development, handling newline characters in text content is a common requirement.Sometimes we want to display the text entered by the user in a structured paragraph format, and sometimes we only want to simply convert each newline into an HTML line break tag.At this point, the `linebreaks` and `linebreaksbr` filters come into play.They can all handle line breaks, but in actual applications, the generated HTML structures and semantics are quite different.### `linebreaks` filter

2025-11-08