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.