How to safely display HTML or JS code in a template without escaping?

Calendar 👁️ 60

In AnQi CMS template development and content operation, sometimes we need to display HTML code or run JavaScript scripts directly on the page, rather than having them parsed by the browser as plain text.This usually occurs when it is necessary to embed third-party statistical code, advertising scripts, or display code examples in article content.However, Anqi CMS, for security reasons, defaults to escaping output content to templates to prevent security vulnerabilities such as cross-site scripting (XSS).

To safely display HTML or JS code in a template without being escaped, we need to understand several key mechanisms provided by the Anqi CMS.

Understand the default security mechanism of AnQi CMS

Firstly, it is crucial to understand the default behavior of Anqi CMS.As an enterprise-level content management system, AnQi CMS attaches great importance to security from the very beginning.When you enter any content that may contain HTML tags or JavaScript code and try to output it directly in the front-end template, the system will default to performing HTML entity escaping.This means<script>The label will be converted to&lt;script&gt;,<p>The label will become&lt;p&gt;This avoids the execution of malicious code, thus preventing XSS attacks on websites. Although this mechanism may seem inconvenient in some cases, it is an effective defense line.

Unescape:safeThe filter is crucial

When you are sure that the content you need to output is secure and reliable, and you want it to be parsed as an HTML element or executed as JavaScript code by the browser, you can use the security CMS template engine provided bysafefilter.safeThe filter informs the template engine that the content it handles has been explicitly marked as "safe" by the developer, and does not require HTML escaping and can be output directly.

Usage:

Just add it after the escaped variable you need to unescape|safeJust do it.

For example, if you have a variablecustomHtmlStored custom HTML content:

<div>
    {{ customHtml|safe }}
</div>

Or, when you need to embed a JavaScript statistics code:

<head>
    <!-- 其他头部内容 -->
    <script>
        {{ statisticCode|safe }}
    </script>
</head>

Intag-tongji.mdThe document also mentions a similar usage:{{- pluginJsCode|safe }}This indicates that for JS code fragments that need to be executed directly, usingsafefilters is a standard way of processing.

Application scenario:

  1. Rich text embedded in article or page content:If you enter rich text content with complex HTML structures in the content editor backend (for example, custom layouts tables, reference blocks with specific styles), and you want these HTMLs to be correctly parsed by the front-end. Usually, likearchiveDetailRetrieving from the labelContentField, you will see something similar{{archiveContent|safe}}Usage, which ensures that the rich text format of the article content is retained.
  2. Embedding third-party scripts:JavaScript code snippets provided by services such as Google Analytics, Baidu Statistics, and online customer service systems need to be directly inserted into the page.<head>or<body>It can only work normally.
  3. Display code example:If you want to display HTML, CSS, or JavaScript code snippets on a webpage without having them executed by the browser, but also want them to appear in code highlighting or similar formats, it is usually preprocessed into HTML entities on the server side (for example, using a Markdown converter), and then transmitted throughsafeThe filter output maintains its format. However, if it is only for displaying code without execution, it is more recommended to put it in<pre>and<code>Label, and make sure the content itself is properly escaped (or escaped on the server side, thensafeoutput).

Risk warning:

safeThe filter provides flexibility, but it also comes with potential security risks. Once usedsafeIt means you completely trust the content in the variable. If the variable comes from user input or unfiltered external data, it may lead to XSS attacks.Malicious users may inject JavaScript code to steal sensitive information, tamper with page content, or hijack user sessions.Therefore, please make sure to usesafeThe content source of the filter output is reliable and has been strictly filtered and verified.

Local control escaping:autoescapeTag

exceptsafeThe template engine of AnQi CMS also provides a filter,autoescapeTag block used to enable or disable automatic escaping in a specific area.

Usage:

{% autoescape off %}
    <!-- 在这个区块内的所有变量输出都不会被转义 -->
    <div>{{ variableWithHtmlContent }}</div>
    <script>{{ anotherScriptVariable }}</script>
{% endautoescape %}

{% autoescape on %}
    <!-- 在这个区块内的所有变量输出都会强制被转义 -->
    <div>{{ potentiallyMaliciousContent }}</div>
{% endautoescape %}

autoescapeThe tag is used for the scenario where it is necessary to escape multiple variables output within a larger code block, avoiding the need to add it to each variable|safeor|escape.

Special handling of Markdown content

Inhelp-markdown.mdThe document mentions that the new Anqi CMS supports Markdown editor, and after enabling it, the document content will automatically perform the operation of converting Markdown to html.This means that if you write content in Markdown syntax in the background (including HTML or JS code blocks in Markdown format), the system will automatically convert it to HTML and display it.

For words likearchiveDetailTagging for obtainingContentfield, which also supports onerenderparameter to manually control the Markdown rendering behavior:

{# 启用Markdown转HTML #}
<div>文档内容:{% archiveDetail archiveContent with name="Content" render=true %}{{archiveContent|safe}}</div>

{# 不进行Markdown转HTML #}
<div>文档内容:{% archiveDetail archiveContent with name="Content" render=false %}{{archiveContent|safe}}</div>

It is important to note that evenrender=trueConverted from Markdown to HTML, the final HTML output may still be needed|safeThe filter must be displayed and executed correctly in the browser to avoid HTML tags from being escaped again.

Summary

Displaying HTML or JS code securely in Anqi CMS templates, the core lies in understanding and proper applicationsafeA filter. It provides you with the flexibility to bypass default security escaping, but it also requires you to be responsible for the source and safety of the content. Combined withautoescapeUnderstanding tags and Markdown rendering allows you to control the display behavior of template content more accurately, meeting diverse content operation needs while ensuring website security.


Frequently Asked Questions (FAQ)

  1. Why did I directly put HTML code (for example<p>这是一个段落</p>) in the template, but it displayed as text instead of paragraph style?This is the default security mechanism of AnQi CMS at work. To prevent potential cross-site scripting (XSS) attacks, the system will default to escaping all output HTML tags, turning<to&lt;,>to&gt;This browser will not parse it as an HTML element, but display it as plain text.If you are sure that this HTML content is safe and you want it to be parsed normally by the browser, you need to add|safethe filter. For example{{ myHtmlContent|safe }}.

  2. UsesafeAfter the filter, does it mean that any HTML or JS code I embed is absolutely safe?Not at all.safeThe filter only tells the Anq CMS template engine to stop escaping the content. It does not perform a security scan or filter on the content itself. Therefore, it is usedsafeMeans you as a developer or operator, need to be fully responsible for the security of the content.If content is from user input, external API, or other untrusted sources, you must perform strict filtering, verification, and disinfection before the content enters the database or is output to a template to prevent the injection of malicious code (such as XSS attacks).In short,safeIt is a "trust" mark, but the premise of trust is that you have ensured its security.

  3. Can I directly input HTML code or JS script in the content editor of Anqi CMS backend, and thensaferun it through the filter on the front end?Can, but need to differentiate and operate cautiously.

    • HTML code:If your content editor supports rich text editing (such as WYSIWYG editor), the editor itself can usually handle and store HTML. When you usearchiveDetailWith tags to get the article content and add|safeWhen the filter is applied, these HTML tags can be normally parsed and displayed.
    • JavaScript script:Although technically it is possible to enter in the content editor<script>tag and use|safeoutput, but this is not recommended practice. Content editors will usually remove or escape.<script>To avoid potential risks, even if the editor does not remove it, mixing business logic or statistical scripts into the article content will make website maintenance complex and difficult to control versioning.It is better practice to include JavaScript scripts as separate resource files or directly in the template files, and use them when necessary{{ myScriptCode|safe }}such a variable output. Usually it is directly generated bytag-tongji.mdcoordinated by the system variable mentioned in|safeOutput.

Related articles

How to manage and display the homepage banner carousel?

The homepage banner carousel is the face of the website, which not only attracts the attention of visitors in the first place, but also an important carrier for conveying brand information and promoting core products or services.In AnQiCMS, managing and displaying the homepage banner carousel is a straightforward and flexible process, allowing you to easily create an eye-catching visual focus for your website. ### One, manage your Banner content in the background To manage the homepage Banner carousel, you first need to log in to the AnQiCMS backend management interface. Usually

2025-11-08

How to display language switch options on the front-end page and support hreflang attributes?

AnQiCMS as an efficient and flexible content management system provides a solid foundation for users in global content promotion, and its built-in multilingual support feature is the key to achieving this goal.Display language switch options correctly on your website and configure the `hreflang` attribute for search engines, which not only greatly enhances user experience but is also an important step for international SEO optimization.### One, Preparation: Enable AnQiCMS Multilingual Functionality AnQiCMS itself has strong multilingual support capabilities

2025-11-08

How to customize website structured data (JSON-LD) to improve search engine display?

It is crucial to make the website content stand out in the search engine results page (SERP) in today's highly competitive online environment.Structured data, especially JSON-LD format, is the key tool to achieve this goal.It helps search engines better understand the content of the page, thereby giving them the opportunity to display richer and more attractive "rich media summaries" (Rich Snippets), such as the publication date of the article, the author, ratings, product prices, etc., which can significantly increase click-through rates.

2025-11-08

How to format timestamp data into a readable date and time format and display it?

In website operation and content management, we often need to handle various data, among which date and time information is particularly common.However, these data are often stored in a string of seemingly unordered numbers (i.e., timestamps), which is difficult for ordinary users to understand intuitively.AnQiCMS as an efficient enterprise-level content management system fully considers this user's needs, provides a concise and powerful way, helps us convert these timestamp data into a clear date and time format, and present it on the website.AnQiCMS's template engine design借鉴了 Django in English

2025-11-08

How to truncate long text and display an ellipsis?

In website content presentation, we often need to refine some long text content, such as displaying abstracts on article list pages or showing brief descriptions on product cards.If the entire content is displayed directly, it may not only destroy the neat layout of the page, but may also affect the efficiency of users in quickly browsing information.Therefore, truncating long text and adding an ellipsis at the end has become a common strategy to improve user experience.AnQi CMS as an efficient content management system, built-in flexible template filters, can help us easily achieve this function

2025-11-08

How to format floating-point numbers, controlling the number of decimal places displayed?

Website content operation, it is crucial to display numbers accurately, especially floating-point numbers such as prices and statistics, for enhancing user trust and page professionalism.AnQi CMS knows this, providing simple and flexible tools in its powerful template engine, allowing content creators to easily control the display format of floating-point numbers, including decimal places, without delving into complex programming.Next, we will discuss how to use built-in filters in Anqi CMS templates to elegantly format floating-point numbers.### Use `floatformat`

2025-11-08

How to concatenate or replace strings before displaying them?

In AnQiCMS (AnQiCMS) content operation, we often encounter the need to dynamically process strings displayed on the front end of the website.To enhance the user reading experience, optimize search engine inclusion, or maintain consistency in content display, flexibly concatenating or replacing strings is a very practical skill.AnQi CMS, with its efficient template engine based on Go language, provides us with powerful and convenient tools, making these operations easy to implement at the template level.String concatenation

2025-11-08

How to remove extra spaces or characters from a string before displaying content?

During the operation of a website, we often encounter unnecessary spaces, line breaks, or special characters in the content. These 'impurities' not only affect the appearance of the content and the user's reading experience, but may also have a negative impact on the layout of the page and search engine optimization (SEO).AnQiCMS (AnQiCMS) is an efficient content management system that provides flexible and powerful template functions, among which the built-in template filters are the tools to solve such problems.Before you display content on the page, clean the string

2025-11-08