In AnQiCMS template, when processing article content that includes HTML tags, safely outputting is a crucial issue, which directly relates to the security and user experience of the website.Especially when the content of the article may be input by the background rich text editor, or when the comments or messages submitted by users contain custom HTML, it is easy to suffer from cross-site scripting attacks (XSS) if not handled properly.AnQiCMS as a security and efficiency-oriented content management system, provides the corresponding mechanisms to help us meet this challenge.

Understanding Risk: Why is it Necessary to Safely Output HTML?

When displaying content on the website frontend, if user input or rich text editor content is outputted without processing, malicious users may be able to inject malicious JavaScript code. When these codes are executed in other users' browsers, they may cause harm including but not limited to the following:

  • Steal user privacy data:For example, Cookie, Session tokens, etc.
  • Hijack user session:Act on behalf of the user.
  • Tamper with page content:Maliciously modify web pages, publish false information.
  • Phishing Attack:Lure users to click malicious links or submit sensitive information.

Therefore, ensuring that all content containing HTML is strictly reviewed and processed before being output to the front-end is the basic responsibility of website operators.

AnQiCMS的默认安全机制:English转义

AnQiCMS's template engine uses a syntax similar to the Django template engine, which considers security from the beginning. By default, when you use double curly braces{{ 变量 }}When outputting content, the template engine will automatically escape any HTML tags and special characters contained within. This means that like<is escaped to&lt;,>is escaped to&gt;,"is escaped to&quot;such. This automatic escaping is the first and most effective line of defense against XSS attacks.

For example, if the content of your articlearchive.Contentcontains<h1>文章标题</h1><script>alert('XSS');</script>when you use the template directly{{ archive.Content }}When displayed, the browser will show it as plain text:<h1>文章标题</h1><script>alert('XSS');</script>Instead of parsing and executing the HTML and JavaScript code within it.

When do you need to output raw HTML:|safeFilter

Although automatic escaping ensures safety, sometimes we indeed need the page to correctly render the expected HTML format in the article, such as bold, italic, images, links, etc.This content is usually created by backend administrators through rich text editors (such as the document content editor in AnQiCMS backend) with careful editing and formatting.

In this case, we need to explicitly tell the template engine that this content is “safe”, and it should not be escaped. It should be parsed and rendered according to the original HTML structure. AnQiCMS provides|safeFilter to meet this requirement.

Using the method is very simple, add|safeas follows:

{# 假设 archive.Content 包含了管理员通过富文本编辑器输入的HTML内容 #}
<div>
    {{ archive.Content|safe }}
</div>

Pass|safeFilter, the template engine will trust thisarchive.ContentIt is safe and harmless HTML, and it is output to the browser as is, thus normally rendering the style and structure of the article.

Important reminder: |safeThe filter tells the template engine 'This content is safe, please do not escape it'. Therefore, you mustvery sureby|safeThe content being processed is reliable, purified, or input by fully trusted administrators. If used for outputting user-submitted content that has not been processed at all (such as comments or messages), even if|safeIt may also reintroduce XSS risk.

Special processing of Markdown content:render=trueParameters with|safe

AnQiCMS supports Markdown editor, which brings great convenience to content creators.When you use Markdown to write articles in the background, the Markdown text needs to be converted to HTML first before it can be rendered normally on the front end.

ForarchiveDetailThe Markdown format content obtained by the tag (for exampleContentField), AnQiCMS providesrender=trueparameter to control whether Markdown is converted to HTML.

However, simply performingrender=trueThe converted HTML content, if it still contains in{{ }}English output, default still be escaped. So, the correct practice is to userender=trueparameter to convert Markdown to HTML, then cooperate|safeThe filter is used to safely output this HTML:

{# 获取Markdown格式的文章内容,并转换为HTML,然后安全输出 #}
{% archiveDetail articleContent with name="Content" render=true %}
    <div>
        {{ articleContent|safe }}
    </div>
{% endarchiveDetail %}

This way, Markdown text will be correctly parsed into HTML and safely displayed to the user.

Fine-grained control: Other auxiliary filters

Except|safeFilter outside, AnQiCMS also provides some other filters that can assist in the safe handling or formatting of content in specific scenarios:

  • striptagsandremovetags:If you want to display plain text (such as an article abstract) without any HTML tags, you can usestriptagsa filter to remove all HTML tags.{{ archive.Description|striptags }}If you only want to remove specific HTML tags, you can useremovetagsFilter.{{ archive.Content|removetags:"script,iframe"|safe }}These filters are very useful when reducing the amount of information or strictly controlling the format of the content.

  • escapejs:This filter is specifically used to escape special characters in JavaScript code to prevent malicious code from being embedded in JavaScript strings.Although it is rare to directly output article content as JS in AnQiCMS templates, it can be useful in specific scenarios where dynamic generation of JS code is required.{{ "<script>alert('xss');</script>"|escapejs|safe }}

**Practical Suggestions

  1. Trust the source and use with caution|safe:Always use only when you are sure that the content source (such as, from a rich text editor input by a backend administrator) is safe|safeFilter. For any content that users can directly submit (such as public comments, message boards), even if preliminary filtering is performed on the backend, it should be avoided to be used directly|safe,or use a more strict custom purification logic.
  2. Backend purification is the first line of defense:AnQiCMS has built-in content security management and sensitive word filtering features.Fully utilize these background features to purify and verify the content from the source, which is the most fundamental measure to prevent XSS.The processing of the template layer is a second line of defense.
  3. Follow the principle of least privilege:If a piece of content does not need HTML rendering, do not use it|safe。Let the default automatic escaping mechanism of the template engine take effect, which will save you a lot of trouble in terms of security.
  4. Regular security audits:Even with all security measures in place, it is recommended to regularly scan for security vulnerabilities and audit the code of the website to ensure that no risk points are missed.

By understanding the default security mechanism of AnQiCMS and using it appropriately|safeFilters and other auxiliary filters allow us to output articles containing HTML tags in templates efficiently and securely, enhancing the display effects of the website while effectively preventing XSS attacks.


Common Questions (FAQ)

1. Why do I output directly?{{ archive.Content }}, the HTML tags (such as<strong>/<img>) in the article are not rendered, but displayed as plain text?

This is because AnQiCMS's template engine has enabled automatic escaping by default, which is to prevent XSS attacks. When you use{{ 变量 }}The template engine will convert HTML tags and special characters (such as</>/&/") into their HTML entity encodings (such as&lt;/&gt;)。This browser will not parse this content as HTML code, but display it as plain text.|safeFilter.

2.|safefilters andrender=trueWhat are the differences between the parameters? How should I use them together?

render=trueParameters are mainly used to process Markdown formatted content. It tells AnQiCMS'sarchiveDetailThe tag converts Markdown text to HTML format. The resulting output is still a string, and if output directly, it will still be automatically escaped by the template engine. While|safeThe filter tells the template engine that a variable (regardless of its original format or whether it has been converted to Markdown) is now considered safe HTML and can be output directly without escaping again. Therefore, when your article content is in Markdown format and you want to render it as HTML on the front end, you need to userender=trueConvert it to HTML, then use|safeThe filter ensures that this HTML can be correctly parsed by the browser: `{% archive