How to safely output HTML code passed from the backend in Anqi CMS template using the `safe` filter without escaping?

Calendar 👁️ 66

Build and manage websites in Anqi CMS, we often make use of its powerful and flexible template system to present colorful and rich content.The Anqi CMS template engine borrows the syntax of Django templates, bringing us a familiar development experience and powerful features.However, when handling HTML code passed from the backend to the frontend, we encounter an important security mechanism:Automatic escaping.

This article will delve into how to cleverly use in Anqi CMS template,safeFilter, safely and elegantly output the HTML code passed from the backend while avoiding unnecessary escaping.


Understand the template security mechanism of Anqi CMS

AnQi CMS was designed with the intention ofSecurityIt is placed in the core position, which is not only reflected in its high-performance architecture based on the Go language, but also goes deep into every detail of the front-end template rendering. When we obtain data from the database or other backend services and output it directly in the template, for example, the title of an article{{ archive.Title }}Or an introduction{{ archive.Description }}The template engine will default to escaping HTML special characters in this content.

What is escaping?In simple terms, it is the act of<to&lt;, will>to&gt;, will"to&quot;The purpose of doing this is to prevent cross-site scripting attacks (XSS).If user input is not escaped, malicious users may inject malicious JavaScript code or HTML tags into comments, articles, and other content. When other users browse these contents, the malicious code will be executed in their browsers, causing information leakage, page tampering, and other security issues.

This default automatic escaping mechanism is undoubtedly an important defense line for website security. However, in some specific scenarios, we need the HTML code passed from the backend to be rendered by the browserNormal parsing and presentationThis is not escaped as plain text. For example, the rich text editor content on the article detail page usually includes paragraphs, bold text, images, and other HTML structures;Or some custom promotion modules, whose content is itself a carefully designed HTML code.In this case, the default escaping has become an obstacle to our beautiful presentation of content.


safeThe role of the filter: unlock the presentation capabilities of HTML

To solve the above problem, Anqi CMS provides a template engine namedsafe.safeThe core function of the filter is very intuitive: it tells the template engine,“I trust this content, please do not escape it with HTML, output it directly as HTML code.”

When we pass a variable throughsafeAfter the filter is processed, the template engine will consider the content of the variable to be "safe", and it can be rendered directly as HTML code on the page.This way, all HTML tags stored or generated on the backend will be parsed and displayed according to their original intent, rather than displayed as plain text.

Its basic syntax is very simple, just add the pipe symbol to the end of the variable|andsafeand it is done:

{{ 你的变量 | safe }}

Actual application scenarios: When to usesafeFilter?

UnderstoodsafeThe role of the filter, let's take a look at some typical and important application scenarios it has in the actual content operation of AnQi CMS.

  1. Rich text content on article/product detail pages:This is the most common and most important use case. The rich text editor of Anqi CMS backend allows us to edit complex content containing images, links, formatted text (such as bold, italic, lists), and more.When this content passesarchiveDetailFor example, when the label is retrieved at the front endarchive.Contentit is itself a piece of HTML code. If it is not usedsafethen the article content will display with the following content<p>/<strong>Plain text without tags, not the formatting we expect.

    Example:

    not usesafe(Incorrect example, HTML tags will be displayed):

    <div>
        {# archive.Content 此时会被转义,显示原始HTML标签而不是渲染效果 #}
        {{ archive.Content }}
    </div>
    

    Usesafe(Correct example, HTML effects will be rendered):

    <div>
        {# archive.Content 通过 safe 过滤器,其HTML内容将正常渲染 #}
        {{ archive.Content | safe }}
    </div>
    
  2. Custom field stores HTML code:Anqi CMS supports flexibleContent modelandCustom fieldFunction. Sometimes, we create custom fields for specific content types (such as articles, products) to store some content that is not suitable for rich text editors, but still needs to be presented in HTML format, such as a special promotional banner code, an embedded video player code, or a complex product specification table.This is also necessary to retrieve content from these custom fieldssafefilter.

    Example:Suppose we have a custom field namedpromotion_htmlto store promotional HTML code:

    {% archiveDetail promotionHTML with name="promotion_html" %}
    <div class="promotion-area">
        {# promotionHTML 变量中存储的HTML代码将被正确解析 #}
        {{ promotionHTML | safe }}
    </div>
    
  3. Markdown content converted to HTML output:If your content uses a Markdown editor, and the content needs to be processed on the backend or through a specific template filter (such asrenderFilter converted to HTML and then output to the front end, then this converted HTML also needssafea filter to ensure correct rendering.

    Example:AssumearchiveDetailthe tag in processingContentfield throughrender=trueparameter to convert Markdown to HTML:

    {% archiveDetail articleContent with name="Content" render=true %}
    <div class="article-body">
        {# 经过 Markdown 渲染后的 HTML 内容,需要 safe 过滤器来保证其正常显示 #}
        {{ articleContent | safe }}
    </div>
    

Safety risks and **practice: usingsafeAttention事项

safeAlthough filters can help us achieve flexible HTML content display, as its name suggests, it is in“Believe”Content is decrypted under the premise of security. Therefore, it is also a double-edged sword, and if used improperly, it may bring potential security risks to the website.

The most core principle is: only use HTML content from sources that are 'fully trusted'safefilter.

What is a 'fully trusted' source?

  • Content edited and published directly by the administrator in the background:Generally, we consider website administrators to be trustworthy and not to intentionally publish malicious code.
  • HTML content that has been strictly processed and sanitized on the backend:

Related articles

How to automatically identify URLs and email addresses in the text and convert them into clickable links in `urlize` and `urlizetrunc` filters in AnQi CMS?

In Anqi CMS, we often encounter scenarios where we need to display website or email addresses in the article content, comments, or other user input text.If these addresses are only plain text, users will not be able to click and jump directly, which will greatly reduce the user experience of the website.Fortunately, Anqi CMS is built-in with powerful template filters, among which `urlize` and `urlizetrunc` are specifically designed to solve this problem. They can automatically convert identified URLs and email addresses into clickable HTML links.

2025-11-08

How to use the `wordwrap` filter in AnQi CMS template to automatically wrap long text and avoid layout chaos or overflow?

In website content operation, we often encounter situations where the text content is too long, causing page layout chaos, even overflowing the container, which seriously affects the user experience.Especially when a continuous English word without spaces or a long string of Chinese characters appears in a narrow area, the default line break mechanism of the browser may not meet our design requirements.Fortunately, AnQi CMS provides a very practical tool for template developers to elegantly solve this problem - that is the `wordwrap` filter.

2025-11-08

How to quickly count the number of words (or Chinese words) in the content of an article in AnQi CMS using the `wordcount` filter, for SEO or reading time evaluation?

In website operation, the quality and presentation of content are crucial.The number of words in an article not only affects its performance in search engines, but is also a key indicator for evaluating user reading experience and estimating reading time.No doubt, manually counting the number of words in content is a tedious task, especially when the amount of content is vast.Luckily, AnQiCMS (AnQiCMS) has provided us with a small yet powerful tool—the `wordcount` filter, making content word count easy. ### The Importance of Word Count in Content

2025-11-08

How to center, left-align, and right-align Chinese string with specified width using `center`, `ljust`, and `rjust` filters in the Anqi CMS template?

When building and maintaining website content, we often need to pay attention to the visual presentation of information, especially the alignment of text content.It is particularly important to accurately control the centering, left alignment, or right alignment of strings, whether it is for the neatness and beauty of the table or to maintain visual balance within a fixed width area.AnQiCMS with its flexible and powerful template engine, provides us with several very practical filters to easily achieve this goal, even for strings containing Chinese characters.

2025-11-08

The `dump` filter has what practices in debugging Anqi CMS templates, and how to clearly view the structure and value of complex variables?

During the template development process of AnQi CMS, we often encounter the need to view variable content and structure, especially when dealing with complex objects passed from the background.If you cannot clearly know what is inside the variable, debugging will be as difficult as a blind man feeling an elephant.The AnqiCMS adopts the Pongo2 template engine syntax similar to Django, providing rich tags and filters to help us build dynamic pages, one extremely powerful debugging tool is the `dump` filter.### `dump` filter

2025-11-08

How to concatenate the article title (Title) with the system-defined website name (SiteName) through the `tdk` filter and output it to the <title> tag in the Anqi CMS template?

In website operation, the importance of the `<title>` tag is self-evident. It is not only the key for search engines to understand the theme of the page, but also the content that users see first in the search results.A well-crafted page title that can effectively increase click-through rates and have a positive impact on SEO optimization.Therefore, how to organically integrate the core title of the article with the brand name of the website to form an accurate and attractive `<title>` tag is a fundamental and important link in the design of website templates.AnQiCMS as a feature-rich enterprise-level content management system

2025-11-08

How to configure the separator (`sep`) and whether to display the parent category title (`showParent`) for the `tdk` filter in Anqin CMS?

During website operations and SEO optimization, the page title (Title) is a key element to attract user clicks and improve search engine rankings.AnQiCMS provides a flexible `tdk` filter, allowing us to finely control the display of page TDK (Title, Description, Keywords).Among these parameters, `sep` and `showParent` play a crucial role in building page titles with rich hierarchy and clarity.

2025-11-08

How to use the `stringformat` filter in Anqi CMS template to format price numbers as currency (such as “¥%.2f”)?

When displaying product or service prices on a website, we all hope that they look clear and professional, easy to understand.A sequence of price numbers without currency symbols and inconsistent decimal places, which not only affects the appearance but may also raise doubts about the professionalism of the product. 幸运的是,AnQiCMS(AnQiCMS)强大的模板引擎提供了多种实用的过滤器,其中 `stringformat` 过滤器就是将数字格式化为标准货币形式的利器。

2025-11-08