How to ensure that HTML code is correctly parsed and not escaped when displaying rich text content using the `safe` filter?

Calendar 👁️ 76

In Anqi CMS, rich text content usually carries articles, product descriptions, or page details, etc., which often contains various HTML tags such as bold, italic, images, links, tables, etc.If this HTML code is not parsed correctly and is simply displayed as plain text, then what the user sees on the front end is a mess of code, not beautiful and structured content. This obviously has a serious impact on the reading experience and professionalism of the website.

The AnQi CMS template engine uses a syntax style similar to Django, its default behavior is for security reasons, it will escape all output variable content. This means that when you enter in the background rich text editor,<p>这是一段<b>加粗</b>的文字。</p>such content is output directly in the template, if not handled specially, the browser may receive&lt;p&gt;这是一段&lt;b&gt;加粗&lt;/b&gt;的文字。&lt;/p&gt;. At this point,pTags andbTags and the like are escaped into their HTML entities, so they are displayed directly on the page<p>and<b>Characters, not parsed and presented in bold text style by the browser.This escaping mechanism effectively prevents cross-site scripting attacks (XSS), and avoids malicious code being directly injected into the page for execution.

However, for the content we expect to be displayed as rich text by default, this escaping mechanism has become an obstacle. To solve this problem, Anqi CMS providessafefilter.safeThe core function of the filter is to clearly tell the template engine: "This content is safe, do not escape it in HTML, and parse and render it directly according to the HTML code within it."

safeThe core function and usage of the filter

UsesafeThe filter is very intuitive, you just need to add it after the variable that needs to be output and contains HTML code|safeAnd it is: {{ 变量名|safe }}.

For example, in the AnQi CMS template, when you need to display the detailed content of an article, you will usearchiveDetailtags to get the document content fieldContent. At this point, you will getarchiveContentVariables may contain HTML code edited by users through a rich text editor. To ensure that these HTML codes are correctly parsed, you should use it like this:

{%- archiveDetail articleContent with name="Content" %}
{{articleContent|safe}}

Similarly, if you need to display the detailed introduction of the category (categoryDetailofContentfield), the content of a single page (pageDetailofContentfield), or the description of a tag (tagDetailofContentfield), it also needs to be applied|safeFilter:

  • Classification content:

    {%- categoryDetail categoryContent with name="Content" %}
    {{categoryContent|safe}}
    
  • Single page content:

    {%- pageDetail pageContent with name="Content" %}
    {{pageContent|safe}}
    
  • Label content:

    {%- tagDetail tagContent with name="Content" %}
    {{tagContent|safe}}
    

Through such processing, the template engine will no longer perform HTML escaping when outputting these variables, but will instead send the original HTML code directly to the browser, which will be responsible for parsing and presenting the expected rich text style.

safety considerations and **practice

AlthoughsafeThe filter solves the display problem of rich text content, but it must be used with caution as it essentially turns off the default security protection of the template engine. This means that if you willsafeThe filter is applied to user input coming from untrusted sources or that has not been strictly filtered, which may introduce XSS vulnerabilities.Malicious users may submit rich text content containing JavaScript code and execute these scripts on the page, thereby stealing user information, tampering with page content, and so on.

Therefore, **practice is:**

  1. Only applied to trustworthy content: safeThe filter should only be used when you are sure that the content is safe and harmless, such as reviewed by a background administrator or generated by the system.
  2. Utilizing the built-in security mechanism of CMS:The AnQi CMS itself provides multi-layer security mechanisms, such as sensitive word filtering, content security management, and other functions. When usingsafeBefore the filter, make sure that the relevant content has passed these built-in security checks.
  3. Processing Markdown content:If you have enabled the Markdown editor, Anqi CMS will automatically convert Markdown syntax to HTML when saving or outputting content. In this case,safeThe filter is still necessary to ensure that the converted HTML code can be parsed correctly. The document mentions that,archiveDetailtags can even acceptrender=trueSpecify the parameter to explicitly perform the Markdown to HTML conversion, and then cooperate|safeEnsure rendering.

In short,safeThe filter is an indispensable tool in Anqi CMS for handling rich text content, allowing the page to display beautiful and structured content correctly.But while enjoying its convenience, always keep in mind its security features, and apply them to trusted, disinfected content, which is the key to ensuring the stable operation of the website.


Frequently Asked Questions (FAQ)

  1. Q: If I forget to use the rich text content|safeWhat will happen to the filter?A: If you forget to use|safethe filter, all HTML tags (such as<p>,<b>,<img>etc.) will be escaped by the template engine into HTML entities (such as&lt;p&gt;,&lt;b&gt;,&lt;img&gt;Then it is displayed as plain text on the page. The user will see the original HTML code, rather than rendered bold text, images, or formatting effects.

  2. Q:|safeFilters and{% autoescape off %}What are the differences between tags?A:|safefilter is fora single variableActive, it will cancel the HTML escaping of the variable content. And{% autoescape off %}Is aTemplate TagIt can be used to closea template code blockthe automatic HTML escaping of all variables. Usually,|safeUsed to precisely control the output of specific variables, while{% autoescape off %}is used for large-scale, known-safe template areas. For safety reasons, it is recommended to use as much as possible|safeFilter to minimize the scope of automatic escaping.

  3. Q: I inserted JavaScript code in the backend rich text editor and then used|safeFilter, why did this JS code execute on the front end? Is it safe?A: That's exactly|safeThe reason to use the filter cautiously. When you use|safeWhen using a filter, you are telling the template engine that this content is 'safe' and does not require escaping processing.If the content contains JavaScript code, the template engine will directly output it to the page, and the browser will execute it as part of the page script.This is very unsafe because malicious users can exploit this mechanism to carry out XSS attacks. Therefore,Never do thisto|safeThe filter is applied to any content that may contain JavaScript code submitted by users or not verified, even if it is inserted in the background, it should ensure the reliability of the content source. The rich text editor of Anq CMS usually has a certain filtering mechanism, but developers and operators should understand|safeThe risk is crucial.

Related articles

How to use a filter to automatically find URLs in text and convert them into clickable HTML links?

In website operation, we often encounter such needs: in the content or description of the article, some URLs or email addresses may be included, but they are just plain text, and users cannot click to access directly.Manually adding HTML links to each URL is inefficient and prone to errors, especially when the volume of content is large.AnQiCMS (AnQiCMS) understands this pain point and provides powerful built-in filters to help us easily automate the conversion of URLs in text, making website content more friendly and convenient.### Automated Link

2025-11-08

How to use a filter to remove specific characters (such as spaces) from the beginning, end, or any position of a string?

String cleaning practical guide in AnQiCMS: Efficiently remove filters for specific characters During the operation of a website, we often encounter situations where we need to clean and format string data.Whether it's the extra spaces typed by users or redundant characters carried in when importing content from external sources, these subtle details may affect the neatness of website content and the user experience.AnQiCMS (AnQiCMS) provides a multifunctional and easy-to-use template filter that can help us easily deal with these string cleaning needs.

2025-11-08

How to set a default display value for a possibly empty variable, string, or object?

In website content management, the integrity and consistency of data are crucial.However, in actual operation, we often encounter situations where certain variables, strings, or objects may be empty.If the template does not handle these null values properly, the front-end page may appear blank, disordered, or even report errors, severely affecting user experience.AnQiCMS provides various flexible and powerful template tags and filters, helping us elegantly handle potential null values to ensure the stability and beauty of website content.The AnQi CMS template system borrows the syntax from Django

2025-11-08

How to perform addition or other arithmetic operations on numbers or strings in the template?

In website template development, we often need to perform some basic arithmetic operations, such as calculating the sum, adjusting values, or comparing values based on specific conditions.AnQiCMS (AnQiCMS) boasts an efficient architecture based on the Go language and a flexible template engine inspired by the Django style, providing users with an intuitive and powerful way to perform arithmetic operations such as addition of numbers or strings in templates.

2025-11-08

If the article content is in Markdown format, how to use the `render` filter to render it as HTML?

AnQi CMS is favored by many users for its efficient and flexible content management capabilities.In content creation, Markdown format has become the preferred choice for many content creators due to its simplicity and efficiency.But how to beautifully present these Markdown-formatted contents as structured HTML on the website front-end is a concern for many users.

2025-11-08

How to dynamically output the SEO title, keywords, and description (TDK) on AnQiCMS templates?

The performance of a website in search engines directly affects the efficiency of content access, and the title (Title), keywords (Keywords), and description (Description), abbreviated as TDK, are the 'business card' for search engines to understand page content.Effectively manage and dynamically output TDK, which can significantly improve the SEO effect and click-through rate of the website.AnQiCMS is a content management system that highly values SEO and provides flexible and powerful features, making it easy to dynamically configure page TDK.

2025-11-08

How to use the `languages` tag to build a language switch menu and output the `hreflang` tag in a multilingual site?

Building multilingual sites in AnQiCMS (AnQiCMS) can not only expand your market range but also provide a more user-friendly access experience for users in different regions.To achieve this goal, the core lies in effectively utilizing the `languages` tag to create a language switch menu and correctly output the `hreflang` tag to optimize search engine recognition.AnQiCMS is a content management system that focuses on enterprise applications, with its powerful multilingual support being one of its highlights.It allows you to create multiple language versions for website content

2025-11-08

How to get and display the system parameters configured in the global settings of the AnQiCMS template?

In the AnQiCMS template, efficiently obtaining and displaying the system parameters configured in the background "Global Settings" is the key to ensuring unified website information and convenient management.AnQiCMS provides a set of intuitive and powerful template tags, allowing developers and operators to easily achieve this goal without delving into complex programming code.

2025-11-08