As an experienced AnQiCMS website operator, I am well aware of the importance of content security output, while also ensuring the complete presentation of high-quality content.In AnQiCMS template development, dealing with HTML content often encounters a core issue: how to ensure that these HTML contents are rendered as expected and not escaped to plain text by the template engine?This not only involves the display effect of the content, but also concerns the security of the website.
AnQiCMS uses a syntax similar to the Django template engine, one of its core design philosophies is security. This means that when you output variables directly in the template, for example{{ 变量 }}The template engine will default to escaping HTML special characters. For example,<div>Hello</div>Will be escaped to<div>Hello</div>, the browser will display it as plain text, rather than rendering it as an HTML element.This default automatic escaping mechanism is an important security measure to prevent cross-site scripting attacks (XSS).It effectively prevents malicious users from damaging websites or stealing user data by injecting HTML or JavaScript code.
However, in the actual content operation, we often need to output content that inherently contains valid HTML structure.For example, through the AnQiCMS backend rich text editor, the article content may contain paragraphs, images, links, and other HTML tags.If this content is also escaped, then the front-end display of the website will be problematic, and the user will see a chaotic HTML source code.To solve this problem, AnQiCMS provides a clear way to indicate to the template engine which content is trusted and safe HTML that does not require escaping.
UsesafeThe filter explicitly marks safe HTML.
In the AnQiCMS template, the most commonly used and direct method is to usesafeFilter. When you are sure that the HTML content contained in a variable is safe and needs to be output as is, you can apply it.|safeThe filter informs the template engine that the value of this variable is 'safe' HTML, which can be safely output directly without escaping processing.
For example, on the article detail page, we usually retrieve the main content of the article from the database.This content has been edited by the backend rich text editor and inherently contains HTML tags.At this time, you need to ensure that they can be rendered correctly. You can use it like this|safeFilter:
{# 默认用法,自动获取当前页面文档,并安全输出其内容 #}
<div>文档内容:{% archiveDetail archiveContent with name="Content" %}{{archiveContent|safe}}</div>
{# 对于自定义字段,如果也可能包含HTML,同样可以应用 `|safe` #}
{% archiveDetail myCustomHtmlField with name="MyCustomHtmlField" %}
<div>我的自定义HTML字段:{{myCustomHtmlField|safe}}</div>
Please note,archiveDetailthe tag in processingContentWhen a field is processed, if the background has enabled the Markdown editor and setrender=trueit will first convert Markdown to HTML. At this point,|safeIt is still the key to ensure that the converted HTML is not escaped.
UtilizeautoescapeTag controls block escaping
In addition to using for individual variables:safeIn addition to the filter, AnQiCMS also providesautoescapeThe tag is used to control the automatic escaping behavior of HTML in a specific block of the template.This is very useful when you need to handle multiple variables that may contain HTML within a code block, or when you want to temporarily disable automatic escaping.
autoescapeTags have two states:onandoff.
{% autoescape on %}: Explicitly enable HTML auto-escape, even if it is already enabled by default.{% autoescape off %}: Disable HTML auto-escape.
One usageautoescape offAn example of a tag is as follows:
{% autoescape off %}
<p>以下内容将不会被自动转义:</p>
<div>
{{ some_html_variable }}
{{ another_html_string }}
{# 这里的 <script> 标签如果来自变量,也不会被转义,需要特别小心 #}
{{ "<script>alert('Hello from AnQiCMS!');</script>" }}
</div>
{% endautoescape %}
Use{% autoescape off %}Be extra careful when using tags. It will affect the output of all internal variables, meaning any unsterilized user input that is output within this block may introduce an XSS vulnerability.Therefore, unless you have full trust and control over the sources and security of all the content within this block, it is not recommended to use this label extensively.In most cases, for the use of a specific variable|safeFilters are a more refined and secure approach.
**Consideration of Practice and Safety**
As a website operator, security is always the top priority when outputting HTML content in the AnQiCMS template.
- Trust the source of content.: Only for content created or strictly filtered and verified by the AnQiCMS backend rich text editor
|safeFilter. This content is usually considered trustworthy. - Never trust user input directly.For any original input content submitted by users, such as comments, messages, or other raw data that has not been processed by the backend, do not use it directly even if you think it is HTML
|safeor{% autoescape off %}These contents must be strictly purified and verified by the server-side HTML to ensure that no malicious scripts are included. - Understand the riskEach time use:
|safeOr filter.{% autoescape off %}Tags mean that you are taking on the risk that this part of the content may introduce an XSS vulnerability. Always assess and understand these risks. - Review codeRegularly review template code, especially that which uses
|safeorautoescape offparts, ensuring their use is reasonable and safe.
By appropriately applying|safefilters and using them cautiously when necessaryautoescapeLabel, you can effectively control the output of HTML content in the AnQiCMS template, ensuring the correct rendering of website content and maintaining the security of the website.
Frequently Asked Questions
Why does the AnQiCMS template default to escaping HTML content?
The AnQiCMS template engine defaults to escaping HTML for website security considerations, the main purpose is to prevent cross-site scripting attacks (XSS). By using>/</&Special characters are escaped to HTML entities, the template engine can ensure that malicious users cannot execute unauthorized operations by injecting HTML or JavaScript code into the input, thereby protecting the website and user safety.
If I need to output containing<script>how to operate the code snippet labeled
In most cases, it is strongly recommended not to output containing directly in the front-end template<script>Tag code snippet, especially when this code may come from user input, as this poses a significant security risk. If under specific scenarios (for example, content is obtained from a completely trusted source and has been strictly verified and sanitized on the backend) it is indeed necessary to output this type of HTML, you can use|safea filter. For example:{{ trusted_script_content|safe }}In practice, it is best to avoid this approach, or encapsulate the script logic in an external JavaScript file and pass data dynamically through the backend instead of directly passing the script code.
|safeFilters and{% autoescape off %}What are the differences between tags?
|safeFilters and{% autoescape off %}Tags are all used to disable HTML escaping in functionality, but their scope and usage scenarios are different.|safeThe filter is applied to a single variable, it only tells the template engine that the value of the current variable is safe and does not need to be escaped. And{% autoescape off %}The tag is a block-level tag that turns off the automatic HTML escaping of all variables inside it until it encounters{% endautoescape %}Thus,|safewhich provides finer control,autoescape offIt affects a larger code block, and a more comprehensive security assessment is needed when used.