How to correctly display HTML rich text content in article content using the `safe` filter?

Calendar 👁️ 77

In website content operation, rich text content plays a vital role.It allows us to enrich the expression of the article with various formats such as images, links, bold, italic, and more, enhancing the reading experience.AnQiCMS (AnQiCMS) provides a powerful backend editor, making it easy for us to create all kinds of wonderful content.However, when this rich text content is finally displayed on the website, one may find that the originally beautiful formatting and links have become the original HTML code string. Why is that?

Rich text content and default escaping mechanism in AnQi CMS

The AnQi CMS supports inserting HTML tags, images, videos, and various rich text elements in the backend content editor.When you edit and save articles, category descriptions, or single-page content through the backend editor, this rich content will be stored in the database in HTML format.

By default, to ensure the security of the website and prevent potential risks such as cross-site scripting (XSS) attacks, the template engine of AnQi CMS automatically performs 'escaping' processing on the HTML content obtained from the database and outputted to the page. This means that all HTML tags (such as<p>,<a>,<img>Angle brackets in the<and>Will be replaced with&lt;and&gt;Characters such as HTML entities. This processing method ensures that the browser treats this content as plain text rather than executable code, thus avoiding potential security vulnerabilities.But it also leads to the display of the original HTML code on the page, rather than the rich text style you expected.

safeThe role of the filter: unlock the correct display of rich text

To solve the problem of rich text content being escaped, the template engine of Anqi CMS providessafefilter.safeA filter, by its very name, tells the template engine that the content decorated by it is "safe", does not require HTML entity escaping, and can be output directly as HTML code to the page. By applyingsafeA filter, and the browser can correctly parse and render rich text content, restoring its original formatting, images, links, and styles.

How to use correctly in article contentsafeFilter

In the Anqi CMS template files, when we obtain the rich text content of articles, categories, or single pages, we usually use specific tags to retrieve data. For example, to obtain the detailed content of an article, we might usearchiveDetailLabel, assign the content to a variable:

{# 假设您正在获取当前文章的完整内容,并将其赋值给 archiveContent 变量 #}
{% archiveDetail archiveContent with name="Content" %}

Make sure that this part of the content is displayed correctly in rich text. You need to do this when outputting the variable.safeThe filter is applied to it. The specific method is to add it to the variable name.|safe.

Let's demonstrate with a typical example:

<div class="article-body">
    {# 这里是关键:将 safe 过滤器应用到 archiveContent 变量上 #}
    {{ archiveContent|safe }}
</div>

In this example,archiveContentThe variable contains the HTML content entered in the article editor. If not|safe,{{ archiveContent }}it will output the escaped HTML string (for example, you will see&lt;p&gt;文章内容&lt;/p&gt;). And add|safeafter,{{ archiveContent|safe }}The original HTML code will be output directly (for example,<p>文章内容</p>), the browser will render it as rich text content with styles, images, and links.

Similarly, if you are getting category content (usingcategoryDetailtags) or single page content (usingpageDetailtags) that contains rich text fields (such asDescriptionorContent), the same method should be applied.safeFilter:

{# 示例:显示分类详情的富文本描述内容 #}
{% categoryDetail categoryDescription with name="Description" %}
<div class="category-description">
    {{ categoryDescription|safe }}
</div>

{# 示例:显示单页面详情的富文本内容 #}
{% pageDetail pageContent with name="Content" %}
<div class="page-content">
    {{ pageContent|safe }}
</div>

Safety considerations: use with cautionsafeFilter

ThoughsafeThe filter is the key to displaying rich text content, but its use requires special caution.As mentioned earlier, it will disable the default security escaping mechanism of the template engine.This means that if your article content is input from an untrusted source, or if the backend editor fails to effectively filter out malicious code (such as JavaScript scripts), then it is directly usedsafeThe filter may cause an XSS (Cross-site Scripting) vulnerability. Attackers may steal user data or hijack user sessions by inserting malicious scripts into the article.

Therefore, when usingsafeWhen filtering, please ensure that:

  1. The source of content is reliable: All rich text content entered through the backend editor should be created by trusted administrators or content editors.
  2. Backend filtering is perfect: The AnQi CMS backend editor usually has certain security filtering capabilities, but it is still necessary to pay attention to system updates to ensure the effectiveness of the filtering mechanism.
  3. Avoid using uncleaned dataDo not directly use third-party data that is untrustworthy and not strictly cleaned and verified on the server side withsafeFilter combined use.

Summary

safeThe filter is an indispensable tool for correctly displaying rich text content in the Anqi CMS template.It allows you to present articles, categories, or single pages in rich formats on the page.But while enjoying its convenience, please always remember the security implications behind it, always put content security first, and ensure the healthy and stable operation of the website.


Frequently Asked Questions (FAQ)

  1. Question: Why haven't I usedsafeThe filter, pictures and links cannot be displayed, only the display is shown.<img>and<a>Tag code?Answer: This is because the Anqicms template engine defaults to escaping all output content to prevent malicious script injection. When you do not usesafefilterers, the angle brackets<and>It will be converted to&lt;and&gt;HTML entities, which cause browsers to be unable to recognize them as HTML tags, but to display them as plain text.

  2. Can I usesafeDoes the filter display HTML content obtained from an external API?Answer: It is principle that can, but it is strongly not recommended to do so directly. Any HTML content from unreliable sources, when usingsafeBefore the filter, strict cleaning and verification should be performed on the server side to filter out potential malicious scripts or unsafe tags.This is to avoid directly outputting unsafe external content to your website, which may cause XSS attack risks.

  3. Question: Besides,safeFilters, are there any other similar filters?Answer: In the Anqi CMS template filter,safeit is used specifically to remove HTML encoding. The opposite of this isescapeFilter (or its aliaseIt is used to force HTML entity escaping (even though it is done by default). Moreover, there is alsoescapejsFilters are used to escape JavaScript code, each serving different security or formatting needs. Usually, when handling the correct display of rich text content,safeThe filter is the most direct and commonly used choice.

Related articles

How to display both subcategories and the list of articles under the category on a category page?

When operating the AnQiCMS website, we often encounter such a need: on a category page, we not only want to display the list of articles under the category but also clearly list all its subcategories to facilitate users in making more detailed navigation.The Anqi CMS, with its flexible template engine and rich built-in tags, can fully help us easily achieve this goal. ### Understanding AnQi CMS Category Page and Template Mechanism In AnQi CMS, each category (whether it is an article category or a product category) can be associated with an independent template file. Generally speaking

2025-11-09

How to manage and display category Banner images and thumbnails?

In website operation, the category page is an important link in guiding users to browse and deepen the brand impression.To configure a unique banner image and thumbnail for the category page, it can not only enhance the visual appeal of the website, but also allow users to intuitively understand the category content, effectively optimizing the user experience.AnQi CMS provides flexible and easy-to-operate functions in this regard, helping us manage and display these visual elements efficiently.

2025-11-09

How to dynamically filter and display a list of articles through URL parameters or search keywords?

Today, with the increasing refinement of content management, how to make your website content smarter and more considerate in serving visitors is the key to improving user experience and website value.AnQiCMS (AnQiCMS) is an efficient and flexible content management system that provides powerful functions to help us achieve this, especially in terms of dynamic filtering and displaying article lists. The combination of template tags with URL parameters allows for easy construction of highly customizable content presentation methods.This article will give a detailed introduction on how to use URL parameters and search keywords

2025-11-09

How to embed and display a留言验证码in a front-end form?

In website operation, the message board and comment area are often important channels for interaction with users.However, the garbage information and malicious submissions that follow are also a headache.An effective method of integrating captcha functionality to filter out this noise.Today, let's talk about how to easily embed and display a message captcha in the frontend form of AnQiCMS (AnQiCMS), building a defense line for your website.

2025-11-09

How to use filters in a template to format displayed numbers and strings (such as decimal places, case conversion)?

In website content presentation, the aesthetics and readability of the data are as important as the quality of the content itself.AnQiCMS (AnQiCMS) provides powerful filter (Filters) functions at the template level, allowing us to easily format numbers and strings displayed on the page, thereby enhancing user experience and the professionalism of page information. ### Filter: A process in data processing We can imagine a filter as a series of processes that handle data.Raw data is like unprocessed raw materials, after the processing of the filter, it can be shaped into what we need

2025-11-09

How to add special styles to specific items when displaying in a list, based on the count in a for loop?

In website content display, we often need to highlight specific items in the list visually, whether it is to attract the attention of users or to enhance the hierarchy of the content.For example, you may want to add a "pin" mark to the latest few articles published, or make the odd and even rows of the list display different background colors to enhance readability.AnQiCMS (AnQiCMS) flexible template engine, which provides powerful support for these refined controls.AnQiCMS's template system borrows the syntax of the Django template engine

2025-11-09

How to implement the automatic display of content collected on the website front end?

How to automatically display the collected content on the website front-end is a concern for many content operators.AnQiCMS (AnQiCMS) is an efficient and flexible content management system that provides a complete solution from content entry to front-end display.It goes through a powerful content model, flexible template tags, and a friendly SEO mechanism, making this process simple and efficient.Next, we will explore how to use the various functions of AnQiCMS to automatically and beautifully display the valuable content you collect on the website's front-end.###

2025-11-09

How to prevent HTML tags from being automatically escaped when content is displayed?

When using Anqi CMS to manage website content, you may encounter a seemingly small but annoying problem: the formatted HTML code entered in the background editor is displayed as plain text on the front page, even presented directly in the form of angle brackets, losing the original style and layout.This not only affects the appearance of the page, but also discounts the carefully arranged content.Why is that, and how should we solve it?###

2025-11-09