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

Calendar 👁️ 84

In the AnQiCMS template system, the core of our daily content display cannot do without the processing of HTML tags.To ensure the security of the website, AnQiCMS defaults to automatically escaping HTML for variables output in templates.This mechanism effectively prevents the injection of malicious code, such as common cross-site scripting attacks (XSS).However, in some cases, we may need to display rich text content containing HTML tags, and at this point, we need to understand how to flexibly control this automatic escaping function.

Automatic escaping: the first line of defense for website security

The AnQiCMS template is developed based on the Go language, drawing inspiration from the Django template engine syntax, one of its core concepts is security first. When the template engine outputs a variable, for example,{{ some_variable }}ifsome_variablehas a value of<script>alert('xss');</script>The output to the page will be escaped by default&lt;script&gt;alert(&#39;xss&#39;);&lt;/script&gt;. The browser will recognize it as plain text rather than executable script, thus ensuring the security of website access.This is a default behavior that is an important security feature of the system, which greatly reduces the risk of security vulnerabilities caused by inappropriate content output.

autoescapeTag: Regional control of HTML tag escaping

autoescapeThe tag is a powerful tool in the AnQiCMS template used to control HTML automatic escaping. It allows you to specify an area of the template where automatic escaping is enabled (on(Should the automatic escaping be turned off?off). This provides regional flexibility in handling content from different sources.

{% autoescape off %}: Turn off automatic escaping for a specified region.

When you are sure that the content within a template area is trustworthy and needs to be rendered according to its original HTML structure, you can use{% autoescape off %}tags to wrap this area.

For example, assume you have a variableproduct_descriptionIt stores the product description entered in the backend rich text editor in HTML format:

{% autoescape off %}
    <div class="product-detail">
        <h3>产品描述</h3>
        {{ product_description }}
    </div>
{% endautoescape %}

In this code block,product_descriptionThe content will not be automatically escaped by AnQiCMS, but will be rendered directly with the included HTML tags. This means that ifproduct_descriptionhas a value of<p><strong>这是产品详情。</strong></p>That means, on the page, 'This is the product details.' will be displayed in bold.

{% autoescape on %}: Explicitly enable automatic escaping (reopen in the closed area)

Although AnQiCMS is enabled by default for automatic escaping, but{% autoescape on %}tags allow you to be in a tag that has already been{% autoescape off %}Close the escaped region and re-enable automatic escaping for a sub-region. This is very useful when outputting mixed content.

Consider the following scenario: In an area where automatic escaping is turned off, you have both HTML content from rich text and unprocessed user input.For safety, you need to ensure that the user input is still escaped.

{% autoescape off %}
    <div class="article-content">
        {# 这里的内容(如 article.content)不会被自动转义 #}
        {{ article.content }}

        <div class="user-comments">
            <h3>用户评论</h3>
            {% for comment in comments %}
                <p>
                    <strong>{{ comment.user_name }}:</strong>
                    {# 重新开启自动转义,确保用户评论内容安全 #}
                    {% autoescape on %}
                        {{ comment.text }}
                    {% endautoescape %}
                </p>
            {% endfor %}
        </div>
    </div>
{% endautoescape %}

In the above example,article.contentIt will not be escaped, butcomment.textEven in a largeautoescape offblock, it will also be because of the nested{% autoescape on %}Labels can regain the protection of automatic escaping.

safeFilter: Fine-grained control for a single variable

exceptautoescapeAnQiCMS also provides this regional control method for tags,safeA filter used toa single variableperform more fine-grained escaping control. When you add|safeIt will explicitly tell the template engine that the value of this variable is 'safe' HTML and does not need to be escaped.

UsesafeFilters are typically used for those cases where you are very sure that the HTML code contained is trustworthy and harmless, such as content obtained from a backend rich text editor.

{% set trusted_html = "<p><em>这段内容是加粗斜体的。</em></p>" %}
{% set user_input = "<script>alert('恶意脚本');</script>" %}

<p>通过 `|safe` 过滤器渲染的信任 HTML:</p>
<div>{{ trusted_html|safe }}</div>

<p>未经 `|safe` 过滤器处理的用户输入(仍会被自动转义):</p>
<div>{{ user_input }}</div>

In the above code,trusted_htmlIt will be directly parsed as HTML, anduser_inputVariables even if they contain scripts will be safely displayed as text due to the default automatic escaping.

Important reminder: safeThe use of filters should be very careful. Once used|safeYou have given up the security protection provided by AnQiCMS. If the content of the variable comes from an untrusted source (such as form data submitted by the user),Absolutely notUse|safeunless you have strictly filtered and sanitized the content on the server side.

escapeFilter: Explicit forced escaping (useful in certain cases)

escapeFilter (can also be abbreviated as)eThe role of ) is to explicitly escape the content in HTML. In the case of AnQiCMS where automatic escaping is enabled by default, it outputs directly{{ variable }}and use{{ variable|escape }}The effect is usually the same because the default mechanism has already completed escaping.

However,escapeFilter is on{% autoescape off %}An element can function within an area. If you are in an area where automatic escaping is turned off, you need to make sure that the content of a specific variable is escaped, you can use|escapefilter.

{% autoescape off %}
    <p>在这个区域内,默认不进行自动转义。</p>
    {% set user_data = "John Doe & Co. <script>evil()</script>" %}
    <p>原始输出:{{ user_data }}</p> {# 不会转义 #}
    <p>强制转义后的输出:{{ user_data|escape }}</p> {# 会被转义 #}
{% endautoescape %}

In this example,{{ user_data }}Content containing scripts will be directly output, which may pose a security risk.{{ user_data|escape }}It will escape the special HTML characters within it, ensuring safety.

Practical suggestions

  • Keep default automatic escaping:Unless there is a clear and legitimate reason, you should always trust the default automatic escaping mechanism of AnQiCMS. This is the foundation of website security.
  • Use with caution.safeFilter:Use only when the content source is absolutely trustworthy (such as administrators entering in the backend rich text editor)|safeFilter. Avoid marking unverified user-submitted data assafe.
  • Preferred|safeSecond choice,autoescape off:When you need to display HTML content, it is preferable to use a filter for individual variables|safeinstead of using{% autoescape off %}Label to enclose large areas. This can more precisely control what content is 'safe' and reduce potential security vulnerabilities.
  • User input should always be escaped:Any content directly from user input should be considered untrusted. Even inautoescape offthe area, ensure that it goes through|escapea filter or re-enable.{% autoescape on %}Escape processing unless your backend program has already performed strict whitelist filtering and sanitization.

Understand and apply correctlyautoescapetags as wellsafeandescapeThe filter is an indispensable skill in AnQiCMS template development. It can help you display a wide variety of content flexibly while ensuring website security.


Frequently Asked Questions (FAQ)

  1. **Q: Why AnQi

Related articles

How can AnQiCMS templates safely display user-submitted rich text content to prevent potential XSS attacks?

During website operations, displaying rich text content submitted by users, such as article comments, forum posts, or blog content, is an unavoidable requirement.However, there may be malicious scripts hidden in these contents, and if they are displayed without precautions, it may lead to cross-site scripting (XSS) attacks, posing potential threats to website visitors.AnQiCMS (AnQiCMS) has fully considered this security risk in its design and provides a series of mechanisms through its template engine to help us safely handle this type of rich text content.

2025-11-09

What are the respective application scenarios of the `striptags` and `removetags` filters when cleaning HTML code in AnQiCMS templates?

In AnQiCMS template design, we often encounter situations where we need to clean up or simplify the HTML code in the content.This is not just for beauty, but also to ensure the correct display of content, improve page loading efficiency, and even prevent potential security risks.The Aqie CMS provides two very practical filters: `striptags` and `removetags`.Although they are all related to the removal of HTML tags, each has a clear application scenario.### `striptags`

2025-11-09

How to determine whether to truncate text and add an ellipsis (...) in AnQiCMS templates based on content length?

In AnQiCMS website content operation, how to elegantly handle long text content to make it both beautiful and complete on the page is the key to improving user experience.Especially on the list page, card display, or introduction area, overly long text often leads to layout confusion and affects the overall visual effect.AnQiCMS' powerful template engine provides various flexible ways to solve this problem, the most commonly used being the function of text truncation and adding ellipses.The AnQiCMS template system borrows the syntax of the Django template engine

2025-11-09

What is the default return value when the `integer` and `float` filters fail to convert in the AnQiCMS template?

When building a website on Anqi CMS, we often need to flexibly handle and display data in the template.These, `integer` and `float` filters are very commonly used tools when converting values to integers or floating-point numbers.However, have you ever thought about how the system will handle when these filters receive a value that cannot be recognized as a number?In other words, what default values will these filters return if the conversion operation fails?Understanding this is crucial for us to write robust and predictable template logic.###

2025-11-09

How to check if the article content in the AnQiCMS template contains specific keywords and display conditions based on this?

In website content operation, we often need to flexibly adjust the display of the page according to the actual content of the article.For example, if an article mentions a specific product or event, we may want to highlight related purchase links or promotional information on the page;If the content of the article involves sensitive topics, it may be necessary to add additional disclaimers.This requirement for conditional display based on article content can be fully realized in the AnQiCMS template.AnQi CMS uses a template engine syntax similar to Django

2025-11-09

How to judge whether the current item is the first or last item in the `for` loop in AnQiCMS template?

In AnQiCMS template development, we often encounter situations where we need to display data in a list loop, such as article lists, product categories, navigation menus, etc.In these loops, sometimes we need to treat the first or last item in the list specially, such as adding unique CSS styles, displaying different content, or cleverly handling the separators between list items.AnQiCMS uses a syntax similar to the Django template engine, providing us with a very intuitive and powerful tool to solve these common template logic problems.### Core Mechanism

2025-11-09

How to implement the `cycle` tag to alternate the display of different styles or data in AnQiCMS templates?

AnQiCMS provides many practical tags for template development, making content display more flexible and efficient.Among them, the `cycle` tag is such a clever tool that it can help us achieve the alternation of data or styles in loops, making the page content more dynamic and visually attractive. ### Understanding the `cycle` tag: Sequence controller in loops In web design, we often encounter situations where we need to apply different styles to repeating elements or display different types of data in a specific order. For example

2025-11-09

How to skip certain items in the `for` loop of the AnQiCMS template based on specific conditions?

In AnQiCMS template development, we often need to display a series of contents, such as article lists, product lists, or navigation menus.But often, we do not want to display all the data at once, but rather hope to skip a part of it according to certain specific conditions, making the final content displayed more accurate and in line with the user's needs.AnQiCMS uses a syntax similar to the Django template engine, which provides a powerful and flexible tool for us to implement this conditional skipping.To implement `for`

2025-11-09