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<,>Will become>)
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<script>alert('XSS攻击!')</script>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'.
In addition, there is another.{% autoescape off %} {# 假设 dangerous_html_content 包含 <script>alert("XSS")</script> #} <p>原始内容: {{ dangerous_html_content }}</p> {# 不转义 #} <p>转义后内容: {{ dangerous_html_content|escape }}</p> {# 强制转义 #} {% endautoescape %}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<p>这是一段内容</p>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.