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: