How to parse and output HTML code in AnQiCMS template instead of escaping it?

Calendar 👁️ 70

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.

Related articles

How to get the thumbnail of AnQiCMS image resources and display it?

AnQiCMS focuses on visual effects and page loading efficiency in content display, therefore, how to efficiently obtain and display thumbnail images of image resources is a common problem we encounter in daily operations.It is fortunate that AnQiCMS provides a very convenient and flexible way to handle image thumbnails, allowing us to easily meet various display needs. --- ### How to manage and generate image thumbnails in AnQiCMS?

2025-11-07

How to format floating-point numbers and retain a certain number of decimal places in AnQiCMS templates?

In website content operation, we often need to display floating-point numbers such as prices, percentages, ratings, and so on.The precision and display method of these numbers directly affect the user experience and the professionalism of information.AnQi CMS knows this need and provides a powerful and flexible floating-point number formatting function in the template engine, allowing you to easily control the display accuracy of floating-point numbers.Next, we will explore two main methods of formatting floating-point numbers and retaining specified decimal places in AnQiCMS templates: the `floatformat` filter and the `stringformat` filter

2025-11-07

How to automatically wrap long text in AnQiCMS templates for optimized reading experience?

In website content operation, optimizing the reading experience is a key factor in attracting and retaining users.Especially for long text content, if there is a lack of proper formatting and automatic line breaking, users may face issues such as horizontal scrolling and text stacking, which can severely affect reading comfort and even lead to user loss.As an AnQiCMS user, we can take advantage of its powerful template engine and built-in features to easily implement automatic line breaks in long text, thereby greatly enhancing the reading experience of the website content.## The Importance of Understanding Long Text Line Breaks Imagine browsing an article on your phone

2025-11-07

How to define an array and display its content in the template using the AnQiCMS filter?

## Advanced Template Development: Flexibly Define and Display Array Content in AnQiCMS During the template development process of AnQiCMS, we often encounter scenarios where we need to process list data, dynamic configuration options, or generate a series of contents based on specific logic.Although most of the data is obtained through tags from the backend, in some cases, defining and operating on simple data sets directly in the template, especially arrays, can greatly improve the flexibility and efficiency of front-end development and reduce dependence on backend data.

2025-11-07

How to get and display detailed information of user groups in AnQiCMS template?

In AnQiCMS, user group management is one of the core functions for building differentiated services and content monetization systems.It is crucial to display detailed information about user groups accurately in the front-end template, whether it is to provide exclusive content for VIP users or to set access restrictions for users of different permission levels.This not only improves the user experience, but also effectively guides users to understand and upgrade their own permissions.How can we flexibly obtain and display the detailed information of these user groups in the AnQiCMS template?

2025-11-07

How to display the language switch options and hreflang tags on a multilingual site in AnQiCMS?

Building multilingual websites in AnQiCMS and providing convenient language switch options as well as correct hreflang tags is a key step in expanding the international market and improving user experience.AnQiCMS with its flexible architecture provides a clear path to achieve this goal, allowing your website content to accurately reach global users while ensuring search engine friendliness. ### Overview of AnQiCMS Multilingual Implementation AnQiCMS integrates multilingual support with multi-site management functions in its design.This means, each different language version

2025-11-07

How to manage website navigation links and display them on the front page in AnQiCMS?

When building and managing a website, a clear and intuitive navigation system is the foundation of user experience and search engine optimization.AnQiCMS provides a flexible and powerful navigation management mechanism, allowing you to easily organize the website structure and elegantly present it to users. ### One, Back-end Navigation Management: Build the Skeleton of Your Website The navigation management feature of AnQiCMS is located in the "Back-end Settings" menu. Click on "Navigation Settings" to enter.Here, you can build a clear navigation system for the website like stacking blocks.

2025-11-07

How to set contact information in AnQiCMS and display it on the front page (such as phone number, address, WeChat)?

In today's digital age, a website's contact information is not only for displaying information but also a bridge for communication between the enterprise and the customer.Clear and easily accessible contact information can effectively enhance customer trust and promote business conversion.AnQiCMS (AnQi Content Management System) knows this well and provides a simple and efficient way to set up and display various contact methods, whether it's phone, address, or WeChat. Let's take a step-by-step look at how to configure and display this key information in AnQiCMS.### First step: Set your contact information in the background First

2025-11-07