When using AnQi CMS for website content creation and template design, we often encounter a problem related to HTML code display: Why is the HTML code I enter in the background editor displayed as plain text on the front page instead of being parsed into actual HTML elements by the browser?This is actually a content management system that has enabled the default mechanism of HTML content escaping for website security.

This article will delve into how to effectively control the output of HTML code in AnQiCMS templates to ensure they are parsed correctly rather than being escaped.

The default security mechanism of AnQiCMS template

AnQiCMS's template engine adopts a syntax similar to Django templates, one of its core design philosophies is the security of content output. When we use it in the template,{{ 变量 }}When outputting content, the system will automatically escape HTML special characters (such as</>/&/"/'and so on). For example,<p>内容</p>It will be converted into&lt;p&gt;内容&lt;/p&gt;.

This default escaping mechanism is an important safeguard for website security, as it can effectively prevent cross-site scripting attacks (XSS). If a user maliciously injects in comments or any area where input is allowed<script>alert('XSS');</script>This code, by default, will escape it to be displayed as plain text, thus avoiding the execution of malicious scripts.

However, in some cases, we indeed need the output content of the template to be parsed as HTML, for example:

  • Rich text editor (such as AnQiCMS backend document content editor) generated HTML content.
  • Specific content fragments that require custom styles or structures.
  • Embed third-party code (although it is usually not recommended to hardcode a large amount of third-party JS/CSS directly in the template).

Core solution: use|safeFilter

AnQiCMS provides|safeA filter can solve this problem. When you are sure that the content of a variable is safe and needs to be output as HTML, you can explicitly tell the template engine not to escape it.

|safeThe use of the filter is very intuitive, just add it after the variable that needs to output HTML content|safeand it is done:

{{ 变量名|safe }}

Example: Output document content

Assuming you are using a rich text editor to write a document in the background, which includes headings, paragraphs, images, and other HTML structures. In the document detail page template, if you output directly{{ archiveContent }}You may see the original HTML tags displayed as escaped.

To make these HTML tags parsed correctly by the browser, you need to use it like this.|safe:

{# 默认用法,自动获取当前页面文档内容,并使用 |safe 过滤器确保HTML被解析 #}
<div>文档内容:{{ archiveDetail with name="Content" |safe }}</div>

{# 将内容赋值给变量后再使用 |safe 过滤器 #}
{% archiveDetail articleContent with name="Content" %}
<div>
    {{ articleContent|safe }}
</div>

HerearchiveDetailThe tag is used to get the details of the document,with name="Content"specified to retrieve the document'sContentfield. After that, through|safeA filter to ensurearticleContentthe HTML code contained in the variable can be parsed and rendered by the browser. For category details (categoryDetail) and single page details (pageDetail) in theContentField, also the same application method.

Security prompt: |safeThe filter will completely disable HTML escaping for the current variable. This means that if you mix data from untrusted sources (such as user submitted content that has not been strictly filtered) with|safeUsing together, the website may face the risk of XSS attacks. Therefore,Always use only HTML content that you completely trust and confirm does not contain malicious code.|safefilter.The AnQiCMS backend rich text editor content is usually subjected to a certain degree of security processing when saved, so the output is usually safe.

Advanced control:autoescapeTag

except|safeThe filter controls a single variable, in addition, AnQiCMS template also providesautoescapetags to control the automatic escaping behavior of all variables within a code block.

autoescapeThere are two forms of the tag:

  • {% autoescape off %}: Turn off automatic HTML escaping within the current block.
  • {% autoescape on %}: Turn on automatic HTML escaping within the current block (this is the default behavior).

Example: Turn off automatic escaping for a specific code block.

If you have a template fragment that contains multiple confirmed safe HTML variables, you can wrap them up without addingautoescape offafter each variable.|safe.

{% autoescape off %}
    <p>这是一个包含多个HTML变量的区域。</p>
    <div>{{ title_html }}</div>
    <div>{{ description_html }}</div>
{% endautoescape %}

{# 注意:即使在 autoescape off 块内,|safe 过滤器依然会生效,因为它显式声明了安全。 #}
{# 如果在 autoescape on 块内,|safe 过滤器能强制输出HTML,覆盖默认的转义行为。 #}

Handle special cases of Markdown content:renderFilter

AnQiCMS supports the use of Markdown editors for content creation in the background.Markdown text itself is plain text and does not contain HTML tags, but when displayed on the front end, we need to convert it to HTML format.|safe,|renderFilters also become very useful.

|renderThe filter is specifically used to render Markdown formatted text into HTML. IfrenderThe content output by the filter needs to be parsed as HTML instead of being escaped for display, then it is usually used with|safethe filter together.

{# 假设 archive.Content 是Markdown格式的文本 #}
<div>
    {{ archive.Content|render|safe }}
</div>

{# 或者在 archiveDetail 标签内直接使用 #}
<div>文档内容(Markdown渲染):{% archiveDetail archiveContent with name="Content" render=true %}{{archiveContent|safe}}</div>

Here|renderTranslate Markdown syntax to HTML, and|safethen ensure that the converted HTML code is parsed by the browser rather than escaped.

Summary

In the AnQiCMS template, understanding and mastering the escaping and parsing mechanism of HTML content is crucial for building a functional and secure website.

  • The default HTML escaping is AnQiCMS providing security protection for your website.
  • When you need to display rich text editor content or other confirmed safe HTML code, please use|safefilter.
  • You can use for multiple safe HTML variables within a code block{% autoescape off %}Label to simplify the operation.
  • If the content is in Markdown format, please use|renderThe filter to convert it to HTML and配合|safeEnsure the output is correctly parsed.

Always remember, when using|safeMake sure the content source is reliable to maintain the overall security of the website.


Frequently Asked Questions (FAQ)

1. Why does the AnQiCMS template default to escaping HTML code? Isn't this increasing the difficulty of my template development?The AnQiCMS template defaults to escaping HTML code to enhance website security, mainly to prevent cross-site scripting attacks (XSS).If a user submits malicious HTML or JavaScript code in an editable content area (such as comments, a message board), the default escaping mechanism will display it as plain text, thereby avoiding potential attack risks.|safeFilter, but this is a necessary security measure intended to protect your website and users.

2. I have already used the content.|renderFilter, why is HTML still displayed escaped? |renderThe filter is mainly responsible for converting Markdown text format to HTML format. For example, it will convert**粗体**to<strong>粗体</strong>. However,|renderthe filter itself will not disable HTML escaping. If|renderThe content to be parsed by the browser as HTML instead of escaping, you still need to add it after|safeFilter, that is{{ 变量|render|safe }}.|renderResponsible for content formatting,|safeResponsible for ensuring the output is parseable HTML.

3. Use|safeWhat risks does the filter bring? How should I avoid these risks?Use|safeThe filter means you declare that the content of the variable to the template engine is 'safe' HTML and does not require escaping.If the content actually contains malicious scripts (such as from unfiltered user input), these scripts will be executed in the user's browser, leading to cross-site scripting attacks (XSS).

  • Use only content that you completely trust.|safe.For example, the document content generated by the AnQiCMS backend rich text editor is usually safe when saved.
  • Never directly associate unprocessed user input with|safeCombine usage.If it is necessary to display user input, make sure that the content has been strictly filtered and sanitized on the server side before saving it to the database or rendering it to the template.
  • Regularly update AnQiCMSTo obtain the latest security patches and **practices.