How does the AnQiCMS template handle the escaping and unescaping of HTML content?

Calendar 👁️ 67

As an experienced website operations expert, I am well aware of the delicate balance between content safety and flexible display.In AnQiCMS such an efficient and secure content management system, understanding how its templates handle the escaping and unescaping of HTML content is crucial for building a user experience that is both beautiful and secure.AnQiCMS is developed based on the Go language, its template engine inherits many modern web framework security design concepts when processing HTML, including automatic escaping of HTML content.

AnQiCMS default strategy: Safety first

AnQiCMS takes the strategy of automatic escaping (Auto-escaping) by default when rendering HTML content in templates. This means that when you input or read text content from the database in the background that contains HTML special characters (such as</>/&/"/'Characters such as } are automatically converted to their corresponding HTML entities before being output on the page (such as<Will become&lt;,>Will become&gt;)

This default security mechanism is the core defense against cross-site scripting (XSS). Imagine if a malicious user submitted in some input box.<script>alert('XSS攻击!')</script>This code, if the system does not escape, this script will be executed in other users' browsers, causing data theft or page tampering. AnQiCMS's automatic escaping will convert this code into&lt;script&gt;alert(&#39;XSS攻击!&#39;)&lt;/script&gt;The browser will treat it as plain text and thus effectively prevent the attack.

The syntax used by AnQiCMS templates is similar to the Django template engine, this 'default safety' principle is a common practice in modern template engines, aiming to maximize protection for the website and its users from potential security threats.

When do you need to escape? The rendering of rich text content

Although automatic escaping ensures security, but in some cases, we need to display rich text content with HTML tags on the page.For example, you may have edited the article content, category description, or single page content in the background using a rich text editor (such as a Markdown editor or WYSIWYG editor), which includes HTML structures such as titles, paragraphs, images, links, and so on.If this content is still automatically escaped, then what the user sees will be the original HTML code, rather than a beautifully formatted page with styles.

In this case, we need to explicitly tell the AnQiCMS template engine that this content is carefully designed and reviewed HTML that can be safely output directly without escaping.

|safeFilter: Explicitly declare content security

The core tool for reversing escaping of rich text content in AnQiCMS templates is|safeFilter. When you are sure that the content of a variable contains safe HTML and you want the browser to parse it as actual HTML structure rather than escaped text, you can use|safefilter.

For example, on the article detail page, category detail page, or single page detail page, the document content is usually edited with a rich text editor and needs to be presented in HTML format. At this point, you will see a template code similar to this:

{# 文档内容需要以HTML形式显示 #}
<div>
    {%- archiveDetail articleContent with name="Content" %}
    {{articleContent|safe}}
</div>

{# 分类内容如果包含HTML,也需要|safe #}
<div>分类内容:{% categoryDetail with name="Content" %}{{categoryContent|safe}}</div>

{# 单页面内容同理 #}
<div>单页内容:{% pageDetail with name="Content" %}{{pageContent|safe}}</div>

By adding to the variable name|safesuch as{{articleContent|safe}}you have given a clear indication to the template engine: thisarticleContentThe content in the variable is 'safe', please output it as HTML without automatic escaping.

Important reminder: |safeThe filter is a double-edged sword.Only use it when you completely trust the source and security of the content.|safeIt may reintroduce XSS risks.In AnQiCMS, the rich text editor usually performs a certain degree of purification when saving content, but this does not mean you can completely relax your vigilance, especially when doing custom development.

Special handling of Markdown content

AnQiCMS also supports Markdown editor.When the background enables the Markdown editor and enters content in Markdown format, the system will convert it to HTML before storing and rendering.|safefilter.

tag-/anqiapi-archive/142.htmlThe document mentions,ContentThe field is automatically converted from Markdown to HTML when the Markdown editor is turned on. It even providesrenderParameters to manually control whether this conversion is performed. Regardless of whether the conversion is automatic or manual, the final HTML content needs to be parsed by the browser.|safe:

{# 假设archiveContent变量包含了Markdown转换后的HTML,需使用|safe #}
<div>文档内容:{% archiveDetail archiveContent with name="Content" render=true %}{{archiveContent|safe}}</div>

This means,render=trueResponsible for converting Markdown text to HTML tag strings, and|safethen responsible for parsing and rendering these HTML tag strings in the browser.

More fine-grained control:autoescapewith the tag andescapeFilter

AnQiCMS template engine also provides finer granularity control:autoescapeTags andescapefilter.

  • autoescapeTags:This tag allows you to control the enablement or disablement of automatic escaping in specific areas of the template.
    • {% autoescape on %}:Clearly enable automatic escaping in this area (even if the global default is off).
    • {% autoescape off %}: Explicitly turn off automatic escaping in this area. In this area, variables will not be automatically escaped, which is equivalent to adding it to all variables by default.|safeBut please use it carefully, as it will greatly increase XSS risk.
    {% autoescape off %}
        {# 在此区域内,变量不会自动转义,除非您明确使用|escape #}
        <p>这是原始输出: {{ dangerous_html_content }}</p>
    {% endautoescape %}
    
  • escapeFilter:It is|safeThe opposite side, used to explicitly escape content in HTML. Although AnQiCMS defaults to automatic escaping,|escape(or its abbreviation)|eatautoescape offWithin an area, or it is very useful when you need to escape content that has already been marked as 'safe'.
    
    {% autoescape off %}
        {# 假设 dangerous_html_content 包含 <script>alert("XSS")</script> #}
        <p>原始内容: {{ dangerous_html_content }}</p> {# 不转义 #}
        <p>转义后内容: {{ dangerous_html_content|escape }}</p> {# 强制转义 #}
    {% endautoescape %}
    
    In addition, there is another.escapejsA filter used specifically for safely outputting variables in the JavaScript context, preventing JavaScript injection.

Summary: Balancing safety and flexibility.

The AnQiCMS template provides a solid security foundation for website HTML content processing through the default automatic escaping mechanism. It also provides|safeFilter,autoescapetags as wellescapeA series of powerful and flexible filters, allowing content operators and developers to fully display the charm of rich text and HTML content according to actual needs, under the premise of safety.

As website operations experts, our responsibility is to fully utilize these tools, ensuring website security and presenting high-quality, engaging content.Understanding and correctly applying these escape and reverse-escape strategies is a key link in the success of AnQiCMS content operations.


Frequently Asked Questions (FAQ)

1. If I forget to use a filter for rich text content in the template|safewhat will happen?Answer: If your rich text content contains HTML tags (such as<p>/<a>/<img>etc.), but you forget to use|safeA filter, then AnQiCMS's default automatic escaping mechanism will convert the HTML special characters to HTML entities. As a result, the user will see not the rendered HTML, but the original HTML code string, for example<p>这是一段内容</p>It will be displayed as&lt;p&gt;这是一段内容&lt;/p&gt;This usually leads to the page displaying incorrectly or losing style.

2. Can AnQiCMS's default automatic escaping mechanism defend against all XSS attacks?Answer: AnQiCMS's default automatic escaping mechanism is an effective and important defense against reflective XSS and stored XSS attacks. It ensures that content that is not explicitly marked assafeAny user input is displayed as plain text to prevent the execution of malicious scripts.However, preventing XSS is a multi-faceted process, and it requires combining with strict input validation on the backend, data sanitization, Content Security Policy (CSP), and other measures.abuse|safeThe filter is the most common way to introduce XSS risksTherefore, it should only be used when you fully trust the source of the content and have verified its security

3. Can I modify the one that has already been|safeDoes the content that has been unescaped again need to be HTML escaped?Answer: Yes. Although it is not common.

Related articles

How to set a custom template for the document detail page or category list page of AnQiCMS?

As an experienced website operations expert, I am well aware that the flexibility and customizability of a content management system (CMS) are crucial for the long-term development of the website and the user experience.AnQiCMS (AnQiCMS) provides an excellent solution in this aspect with its powerful functions and ease of use.Today, let's delve into how to set up custom templates for your document detail page or category list page in AnQiCMS, making your website content display more personalized and professional.

2025-11-07

How does the AnQiCMS template support adaptive, code adaptation, and PC+mobile mode?

## AnQiCMS template: How to ride the multi-end content display with wisdom and flexibility?In today's fast-paced digital world, it is common for users to access websites through various devices.As experienced website operators, we know that whether a website can provide a smooth and high-quality experience on PCs, tablets, mobile phones, and other terminals is directly related to user retention and business conversion.

2025-11-07

How to define an AnQiCMS template configuration file (config.)?

As an experienced website operations expert, I fully understand the importance of a flexible and powerful content management system for enterprises.AnQiCMS is an excellent platform committed to providing efficient and customizable solutions.In the template ecosystem of AnQiCMS, a seemingly insignificant but powerful file - `config.`, plays a crucial role.It not only defines the basic attributes of the template, but also profoundly affects the behavior and performance of the template in the system.

2025-11-07

Where should the AnQiCMS template files be placed?

## Unveiling the Home of AnQiCMS Templates: Clear Guidance Helps You Customize Easily As an experienced website operations expert, I am well aware of the importance of a flexible and efficient content management system for businesses.AnQiCMS is an excellent platform developed based on the Go language, which not only wins the favor of many users with its high performance and high concurrency features, but also provides great convenience in customization.For operators and developers who want to fully utilize their customization potential and build personalized websites, clearly defining the storage directory of AnQiCMS template files is the first step towards success.

2025-11-07

How to extract a specified part of a string or list in the AnQiCMS template?

In the daily operation of Anqi CMS, we often encounter scenarios where we need to display content in a refined manner.How to flexibly extract the part we want from a string or list, whether it is an article summary, product parameter list, or a user comment excerpt, is the key to improving user experience and page cleanliness.As an experienced website operation expert, I deeply understand the strength and flexibility of AnQiCMS based on Go language and Django template engine. Today, let's delve into how to accurately extract the specified part of a string or list in the AnQiCMS template.###

2025-11-07

How to implement string content replacement in AnQiCMS template?

As an experienced website operations expert, I know that flexibility and efficiency are the key to success in daily content management.How to quickly and accurately adjust the string content on the page in terms of content display, whether it is for SEO optimization, brand consistency, or to meet the ever-changing market needs, it is a core skill we must master.Today, let's delve deeply into how the AnQiCMS template cleverly implements the replacement function of string content, empowering your content operation.

2025-11-07

How to get the current website's system configuration information in AnQiCMS template (such as website name, Logo)?

As an experienced website operations expert, I am happy to discuss with you how to efficiently and flexibly obtain the current system configuration information of the website in AnQiCMS templates.This is not only the foundation of template development, but also the key to ensuring the consistency and maintainability of website information.AnQiCMS is an enterprise-level content management system developed based on the Go language, its concise and efficient design philosophy is also reflected in the use of template tags, making the call of technical information in the template layer extremely intuitive.### Cleverly utilize the `system` tag

2025-11-07

How to get the current page's TDK (Title, Description, Keywords) information in AnQiCMS template?

As an experienced website operation expert, I am well aware that TDK (Title, Description, Keywords) is crucial for the search engine optimization (SEO) of any website, as it is like the facade of the website and a guide for search engines.A meticulously optimized TDK that can make your website stand out in the vast sea of online information, attracting targeted users to click and bringing valuable traffic.

2025-11-07