How to safely output HTML code in the template without escaping in AnQiCMS?

Calendar 👁️ 59

When using AnQiCMS for website template development or content display, you may encounter situations where you need to output HTML code directly on the page, only to find that these codes are automatically escaped, for example,<p>Labels have changed&lt;p&gt;This often confuses friends who first contact. In fact, this is the default measure taken by the AnQiCMS template engine for website security.

Understanding the default security mechanism of AnQiCMS templates

The template engine of AnQiCMS has borrowed the syntax of Django templates, one of its core concepts being security. By default, the template engine will escape all HTML special characters from variable output (such as</>/&/"/'Automatically converts to HTML entities.This mechanism is called "auto-escape", which can effectively prevent common security vulnerabilities such as cross-site scripting attacks (XSS).<script>Tags can be used to execute malicious code, steal user data, or damage the page.

Although this default behavior increases security, when we indeed need to output HTML content generated by a rich text editor or obtained from a trusted source, we need a way to tell the template engine: "This content is safe, please do not escape it."

Use|safeThe filter outputs the original HTML

When you know for sure that the content to be output is safe and contains valid HTML structure, you can use|safeA filter to indicate that the template engine should skip the automatic escaping process and output the original content directly.

The usage method of this filter is very simple, just add it after the variable you want to output.|safeIt can be. For example, in AnQiCMS, you often encounter situations where you need to output article content (archive.Content) categorization content (category.Content) or single page content (page.ContentIn the case of HTML tags being entered through a rich text editor.

You can use it in the template like this:

{# 默认,内容会被转义 #}
<div>{{ archive.Content }}</div>

{# 使用 |safe 过滤器,内容将作为原始HTML输出 #}
<div>{{ archive.Content|safe }}</div>

By adding|safeThe template engine will then convert.archive.Contentof<p>/<img>/<strong>Tags such as HTML should be output as is, instead of being converted&lt;p&gt;/&lt;img&gt;/&lt;strong&gt;The same method also applies to other fields that may contain HTML, such as:

  • Category details description:{{ category.Description|safe }}
  • Single page content:{{ page.Content|safe }}
  • Any field you customize in the background and include HTML tags.

Important reminder:Use|safeBe cautious when using filters. Only use them when you completely trust the source and ensure they do not contain malicious scripts. Otherwise, it may pose a security risk to the website.

Flexible control:autoescapeTag block

Besides using individual variables|safeFilter, AnQiCMS also provides{% autoescape %}tags to control the automatic escaping behavior within a module block. This is very useful for managing larger paragraphs or multiple variables' output.

You can use{% autoescape off %}Close the automatic escaping of a block and use it at the end of the block.{% autoescape on %}or{% endautoescape %}Reopen it.

For example, if you have an area containing multiple segments of content, you want them to be output in their original HTML format:

{# 默认,这里的内容会被转义 #}
<p>这是被转义的普通文本。</p>

{% autoescape off %}
    {# 在这个区块内,所有变量输出将不会被自动转义 #}
    <h3>{{ trusted_title_html }}</h3>
    <div>{{ trusted_body_html }}</div>
    <p>这段内容也直接输出 HTML。</p>
{% endautoescape %}

{# 自动转义再次生效 #}
<p>这是恢复自动转义后的普通文本。</p>

This method is suitable for the HTML content in a specific area that needs to be globally enabled or disabled for escaping, without adding it to each variable separately|safe scenario. Similarly, usingautoescape offWhen labeling, you also need to ensure that all content within the block is completely trusted and secure.

Processing Markdown content output

In AnQiCMS, if you enable the Markdown editor for the content field, the system will first render the Markdown syntax into HTML code when outputting.At this time, you may still need to ensure that the rendered HTML can be displayed correctly.

For content fields that have enabled Markdown, such asarchive.ContentWhen you usearchiveDetailWhen getting content, you can addrender=trueparameter to make the system convert Markdown to HTML first. For example:

{# 获取并渲染Markdown内容为HTML #}
{% archiveDetail archiveContent with name="Content" render=true %}
    {# 即使内容经过了 render=true 处理,最终输出到页面时,依然建议结合 |safe 过滤器使用 #}
    <div>{{ archiveContent|safe }}</div>

Hererender=trueTell the AnQiCMS engine to convert Markdown format to HTML before output. After that,|safeThe filter ensures that the converted HTML code is not escaped again by the template engine, so it can be displayed normally on the page.

**Consideration of Practice and Safety**

To ensure the maximum security of the website, it is recommended to strictly control the content input stage.The AnQiCMS backend rich text editor usually filters out some dangerous HTML tags and attributes, but for custom fields or other content that is not processed by the editor, developers should judge their safety themselves.

In short,|safeThe filter is a powerful tool for outputting raw HTML, but it is also a double-edged sword; used properly, it enriches the content, but used improperly, it poses security concerns. By using it flexibly|safeFilters and{% autoescape %}Label, you can safely and effectively output content containing HTML code in the AnQiCMS template.Always remember that ensuring website security is the top priority while enjoying the flexibility of content display.


Frequently Asked Questions (FAQ)

Q1: Why does the AnQiCMS template default to escaping HTML code?A1: AnQiCMS template engine defaults to escaping HTML code to enhance website security, especially to prevent cross-site scripting attacks (XSS).XSS is a common network security vulnerability, where attackers may inject malicious HTML or JavaScript code into content to steal user data, tamper with pages, or perform other malicious operations.The automatic escaping mechanism converts special characters to harmless HTML entities, thereby neutralizing these potential threats.

Q2: Why do I still need to escape the content I input in the backend rich text editor?|safeCan be displayed correctly on the front end?A2: The backend rich text editor filters out some explicitly unsafe tags and attributes when saving content to ensure the stored content is relatively safe, but this is two independent security layers separate from the automatic escaping of the template engine.The template engine will re-execute automatic escaping when any variable is output to the page.

Related articles

How to truncate a string and add an ellipsis (...) to limit the display length in AnQiCMS template?

In AnQiCMS template development, we often need to refine the content displayed on the website, such as article titles, summaries, or abstracts of a text.If the content is too long, it not only affects the beauty of the page, but may also reduce the user's reading experience.AnQiCMS's powerful template engine provides a simple and efficient method to solve this problem, allowing us to easily extract strings and automatically add ellipses (...) to elegantly limit the display length of content.

2025-11-08

How to format a timestamp (timestamp) into a readable date format for display in AnQiCMS?

In the process of website operation, the effective display time of content publishing or updating is crucial for improving user experience and the readability of content.If time information is presented in the original timestamp format, it is often difficult for ordinary users to understand.AnQiCMS provides a straightforward and flexible way to help you convert these digital timestamps into easily readable date and time formats.### How AnQiCMS handles timestamps AnQiCMS typically uses standard Unix Timestamp format for storing content time information

2025-11-08

How to use a `for` loop to iterate over data and display content in AnQiCMS templates?

In AnQiCMS template development, we often need to display a series of dynamic content, such as the latest article list, product categories, navigation menu items, and even custom parameters.At this point, the 'for loop' has become the core tool for us to traverse these data and display it on the web page.Understand and master the `for` loop, which will greatly enhance the flexibility and development efficiency of the template.### Core Grammar: The Foundation of Data Traversal The `for` loop syntax in AnQiCMS templates is concise and intuitive, borrowing the style of the Django template engine.

2025-11-08

How to use the `if` tag for conditional judgment to control content display in AnQiCMS templates?

How to use the `if` tag for conditional judgment to control content display in AnQiCMS templates?When building website templates, we often need to display or hide specific content blocks based on different conditions.For example, the image will be displayed only when the article has a thumbnail, or the welcome message will be displayed only after the user logs in.In the AnQiCMS template system, the `if` tag is a powerful tool for implementing conditional judgments.It uses a syntax similar to the Django template engine, concise and expressive, making the content display logic clear and easy to understand

2025-11-08

How to automatically wrap long text to a specified length in AnQiCMS template?

In the presentation of website content, the way long texts are displayed is often a key factor affecting user experience and the beauty of the page.When we need to display a long text content, such as an article summary, product description, or detailed introduction, in a more readable and layout-adaptive way, AnQiCMS's template function provides a powerful and flexible solution.AnQiCMS uses syntax similar to Django template engine, with various built-in filters (Filters) that can help us easily format text.

2025-11-08

How to automatically parse a URL string into a clickable HTML link in AnQiCMS template?

In AnQiCMS template development, we often encounter the need: the URL string contained in the content should be automatically converted into a clickable HTML link to enhance user experience and page interactivity.Manually adding links is undoubtedly cumbersome and unrealistic, fortunately AnQiCMS provides powerful template filters that can help us easily achieve this function.AnQiCMS template engine supports Django-like syntax, which includes a series of practical filters that can process variable content.For automatic parsing of URL strings

2025-11-08

How to define and use temporary variables in AnQiCMS templates to simplify content display?

When developing templates in AnQiCMS, we often encounter situations where we need to process some complex data or reuse a certain calculation result.To make the template code more concise, readable, and maintainable, AnQiCMS provides a powerful mechanism for defining and using temporary variables, mainly through the `with` and `set` tags.Reasonably utilizing them can greatly enhance our content display efficiency and flexibility. ### Simplified Content Display: Why do we need temporary variables?

2025-11-08

How to implement the link display for multi-language site switching in AnQiCMS?

In today's globalized digital world, multilingual support for websites has become crucial for reaching a wider audience and expanding market boundaries.AnQiCMS (AnQiCMS) fully understands this need, therefore, it takes multilingual support as one of its core features, aiming to help users efficiently build and manage multilingual websites.This article will focus on how to implement the display of language switch links for multi-language sites in AnQiCMS, supplemented by necessary SEO practices, and provide you with a comprehensive guide.

2025-11-08