In which scenarios must the `safe` filter be used to prevent HTML content from being automatically escaped?

Calendar 👁️ 77

When using AnQiCMS for website content management and template development, we often encounter a problem related to HTML content display: why does the rich text content that I edit in the background display as a pile of raw code with angle brackets on the front end, rather than a beautifully formatted layout? This is actually the effect of the 'auto-escape' mechanism of the AnQiCMS template engine, and to solve this problem,safeThe filter has become the key tool we must master.

Why does automatic escaping occur?

AnQiCMS template engine, by default, will escape all content output to the page. This means that if you enter content in<p>这是一段文本</p>,The template engine will convert it for safety,&lt;p&gt;这是一段文本&lt;/p&gt;. After this processing, the browser will display these escaped contents as plain text, rather than parsing them as HTML tags.

This 'security-first' design philosophy is mainly to prevent a common network attack method - cross-site scripting (XSS).If the template engine does not automatically escape user input content, malicious users can insert malicious JavaScript code in comments, messages, or any other input areas.When other users browse pages containing this malicious code, these scripts will execute in their browsers, potentially leading to serious security issues such as information leakage and session hijacking.AnQiCMS as a system dedicated to providing security solutions, its default automatic escaping behavior is exactly the embodiment of this security consideration.

safeFilter: When must it be used?

Although automatic escaping is for security reasons, but sometimes we really need to display HTML content correctly on the page, such as the layout of articles, custom style codes, images, and links.This is when we need to explicitly tell the AnQiCMS template engine: 'This part of the content is safe, please do not escape it, and parse it directly as HTML for display.'This issafethe function of the filter.

Here are some that we must usesafeTypical scenarios for filters:

  1. Article/Document Details (Archive/Document Content)This is the most common use case. When we write articles in the background using a rich text editor, we will include heading levels (<h1>,<h2>), paragraphs (<p>), and images (<img>), link (<a>)as well as various formats (bold, italic, etc.). These are HTML structures. When we obtain and display the article'sarchiveDetailtagContentfield without addingsafeFilter, all of these HTML tags will be escaped, causing the page to display only the raw code instead of well-formatted text.

    For example, when you want to display the content of an article, the correct way is:

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

    Here|safeIt is to inform the template engine,articleContentThe content in the variable is reliable HTML and can be rendered directly.

  2. Category Details/Single Page Details Content (Category/Page Content)Similar to article details, if we fill in rich text format for categories or single pages in the background category management or single page managementContentContent (for example, a detailed introduction to our page or a detailed description of a category), and throughcategoryDetailorpageDetailtags to retrieve and display this content, and also need to usesafeA filter to ensure that the HTML structure is parsed correctly.

    For example, to display the detailed description of a category:

    {% categoryDetail categoryContent with name="Content" %}
    {{ categoryContent|safe }}
    
  3. Rich text content in a custom fieldAnQiCMS allows us to define additional custom fields for content models or categories. If a custom field is designed to store rich text information (such as product specifications, event descriptions, etc.), and we have indeed used a rich text editor to populate these fields in the background, then we also need to apply it when outputting the values of these custom fields in the template.safefilter.

    Suppose you have a custom fieldproduct_description_htmlIt might be used like this:

    {% archiveDetail productDescriptionHtml with name="product_description_html" %}
    {{ productDescriptionHtml|safe }}
    
  4. The backend configuration may contain HTML fieldsIn the global settings or contact information settings modules of a website, some text fields may also allow administrators to enter a small amount of HTML tags to achieve specific display effects. A common example is the copyright information of a website (SiteCopyright), administrators may wish to include a link to the filing official website in the copyright information<a>.

    For example, display copyright information:

    {% system siteCopyright with name="SiteCopyright" %}
    <p>{{ siteCopyright|safe }}</p>
    

    In this case, usingsafefilter can make<p>or<a>tags are correctly parsed by the browser.

UsesafeAttention事项

AlthoughsafeThe filter solved the problem of displaying HTML content, but we must be aware that it isDisable security protectionswitch. UsesafeThis means you have guaranteed the security and reliability of this content.

  • The source of trust is a prerequisite: Use only sources of content that you completely trust.safeFilter. It usually refers to content created or edited directly by website administrators through the backend rich text editor.
  • Be cautious of user input.:Absolutely notUsing any user input that has not been strictly sanitized (such as comments, messages, user-submitted articles)safeFilter. Because users may exploit this vulnerability to carry out XSS attacks.Even if your AnQiCMS backend editor has a security filtering mechanism, you should be cautious when handling HTML content from external or untrusted sources.
  • Rendering of Markdown contentIf the content is stored in Markdown format and converted usingrender=trueparameters to HTML, then the resulting HTML also needssafeThe filter must be enabled to display correctly.renderThe filter is responsible for converting Markdown to HTML strings, andsafeThe filter is responsible for telling the template engine that this HTML string is safe and can be output as is.

In summary,safeThe filter is a powerful and necessary feature in the AnQiCMS template, which gives us the flexibility to display rich text content.But as a website operator, we should treat it like a double-edged sword, always placing the safety of content and the reliability of sources first, ensuring that the website is both beautiful and safe.


Frequently Asked Questions (FAQ)

Q1: UsesafeDoes the filter mean that the website is not secure?A1: Not so.safeThe filter itself is a neutral tool. It simply tells the template engine that "this content has been confirmed safe, please render directly as HTML.If used to display trusted rich text content edited by the website administrator, it is completely safe.If used incorrectly to directly display users' submitted, unreviewed and unfiltered (sanitization) original HTML content, it would open up a potential cross-site scripting (XSS) vulnerability, thereby making the website unsafe.

Q2: I use Markdown editor to write content in the background, and need to add it when displaying on the front end.safefilter?A2: Yes, still needed. The Markdown editor will convert your Markdown syntax content to an HTML string. When you passarchiveDetailorpageDetailThe tag usually retrieves and displays this contentrender=trueParameters to trigger Markdown to HTML conversion.After the conversion, the output is an HTML string, and the template engine will still automatically escape it.Therefore, you still need to append|safeThe filter, so that the browser can correctly parse and display the converted HTML structure.

Q3: BesidessafeFilter, does AnQiCMS have other ways to control HTML escaping?A3: Yes. AnQiCMS template engine also supportsautoescapeLabel. You can use{% autoescape off %}and{% autoescape on %}To enable or disable the automatic escaping feature within a template code block.{% autoescape off %}The content within the brackets will no longer be automatically escaped, which is equivalent to implicitly applying it to all outputsafeFilter, but this usage is usually not recommended as it may inadvertently introduce security risks. UsuallysafeFiltering applied to a specific variable is a more refined and recommended practice.

Related articles

How do the `urlize` and `urlizetrunc` filters automatically convert URLs in text to clickable links?

It is crucial to present information efficiently and aesthetically in website content operations.Especially when the content contains a large number of URLs or email addresses, manually converting them into clickable links is not only inefficient but also prone to errors.AnQiCMS (AnQiCMS) is well-versed in this, its template system provides the practical filters `urlize` and `urlizetrunc`, which can automatically identify URLs in text and intelligently convert them into clickable hyperlinks, greatly enhancing user experience and content management efficiency.###

2025-11-07

How do the `truncatechars` and `truncatewords` filters control the truncation display of long text and add an ellipsis?

In website content operation, we often encounter such situations: In order to maintain the neatness and consistency of the page layout, we need to truncate the long text, such as in article lists or product summaries.If cut off simply and brutally, it may not only result in incomplete meaning of the text, but may also destroy the text structure containing HTML tags, affecting the aesthetics and functionality of the page.AnQi CMS, with its flexible template engine, provides us with an elegant solution to this problem.Through built-in text filters, we can easily control the display length of long texts and add ellipses at appropriate positions

2025-11-07

How does the `slice` filter accurately extract the specified part of a string or array for display?

In the daily content management of Anqi CMS, we often need to accurately trim the text or data list displayed on the website to better adapt to different layouts, provide content previews, or optimize the user reading experience.At this point, the `slice` filter has become a very practical tool, which can help us flexibly extract the specified part of a string or array.### Core Function: Basic Usage of `slice` Filter The `slice` filter is like a tailor, capable of cutting according to the "scissors" position you provide

2025-11-07

How `list` and `split` filters convert a string to an array and how to process it in a template?

In the powerful template system of Anqi CMS, flexible data processing is the key to building dynamic websites.At times, the data we retrieve from the backend, such as tags, keywords, or custom field values, may be stored as comma-separated strings, but we want to treat them as individual items in the frontend template.At this point, the `list` and `split` filters provided by Anq CMS are particularly important, as they help us convert strings into arrays, thereby enabling more refined control and display in templates.Why do we need to convert a string to an array

2025-11-07

How do the `removetags` and `striptags` filters remove specific or all HTML tags from HTML content?

In Anqi CMS, when managing website content, we often encounter such situations: articles imported from outside, comments submitted by users, or code generated by rich text editors may contain various HTML tags.These tags are sometimes necessary, but more often, they may disrupt the page layout, introduce unnecessary styles, and even pose potential security risks. 幸运的是,AnQiCMS provides two very practical template filters —— `removetags` and `striptags`

2025-11-07

How does the `add` filter work for adding numbers or concatenating strings in templates?

In AnQi CMS template design, we often need to perform some simple data processing, such as adding several numbers to display the total sum, or combining different text fragments into a complete sentence.At this time, the `add` filter is particularly convenient, as it is like a universal connector, capable of handling everything from arithmetic operations on numbers to the combination of text, making your template more flexible and dynamic.

2025-11-07

How `default` and `default_if_none` filters set a default display value for possibly empty variables?

In website content management, we often encounter situations where variable values may be empty.These empty values, if displayed directly on the front-end page, may lead to incomplete content display, page layout disorder, and even a bad user experience.AnQiCMS (AnQiCMS) as a powerful content management system, the Django template engine syntax it adopts provides us with a flexible way to handle such issues.

2025-11-07

How `length` and `length_is` filters are used to check the length of a string, array, or map?

In Anqi CMS template development, flexible handling and displaying data is the key to improving website interactivity and user experience.Understanding how to efficiently detect the length of strings, arrays, or mappings (similar to dictionaries or associative arrays in other programming languages) is the foundation for content operations and template customization.This article will introduce in detail the `length` and `length_is` practical filters in the Anqi CMS template engine, which will help you better control the display of page content.### `length` filter

2025-11-07