How to safely output content containing HTML tags in AnQiCMS templates (e.g., article content)?

Calendar 👁️ 61

Guide to safely output HTML content in AnQiCMS templates

When using AnQiCMS to build a website, we often need to display content with rich formatting, such as article content, product descriptions, category details, or single-page content. This content is usually input through the rich text editor in the background and naturally contains HTML tags such as<p>/<strong>/<em>/<a>How to correctly and safely output this content with HTML tags in front-end templates is a very important issue.If not handled properly, it can cause abnormal display of the page, and in severe cases, it may introduce security vulnerabilities such as cross-site scripting (XSS).

AnQiCMS's template engine design pays great attention to security.It defaults to handling variable content fetched from the backend and outputted to the template in a "cautious" manner.This means, when you use directly{{ 变量名 }}The form of outputting a string containing HTML tags when, for example, the article content, the template engine will automatically escape the HTML special characters in the content to prevent potential XSS attacks. For example,<Will be escaped to&lt;,>Will be escaped to&gt;,"Will be escaped to&quot;This is the case, so the user on the front end does not see the rendered HTML effect, but the original HTML tag string that has not been parsed, for example, the page will display&lt;p&gt;这是一段加粗的文字&lt;/strong&gt;&lt;/p&gt;.

So, when we determine that the content is safe and needs to be rendered in HTML format, how should we handle it? AnQiCMS provides|safeA filter to solve this problem.

Use|safeFilter to safely output HTML content

|safeThe filter tells AnQiCMS template engine: "This content has been confirmed as safe HTML, please render it directly as HTML code without any escaping."

For example, to output the article content (archive.Content), and make the HTML tags effective, we should write the template code like this:

{# 输出文章正文,并允许HTML标签渲染 #}
<div>
    {% archiveDetail articleContent with name="Content" %}
    {{ articleContent|safe }}
</div>

Here, archiveDetailTags are used to obtain the detailed content of the article,articleContentThe variable carries the content of the article. Next, by{{ articleContent|safe }}We instruct the template engine toarticleContenttreat the HTML tags within it as trusted code for parsing and rendering.

Similarly, for other content that may contain HTML tags, such as category descriptions,categoryDetailofContentField, single-page contentpageDetailofContentField) orsystemCopyright information in the tag (SiteCopyright), as long as you confirm that this content is strictly reviewed and free of security risks, it can be used|safeFilter:

{# 输出分类详情中的内容 #}
<div>
    {% categoryDetail categoryContent with name="Content" %}
    {{ categoryContent|safe }}
</div>

{# 输出单页面详情中的内容 #}
<div>
    {% pageDetail pageContent with name="Content" %}
    {{ pageContent|safe }}
</div>

{# 输出系统设置中的版权信息,如果其中包含HTML标签 #}
<div>
    {% system siteCopyright with name="SiteCopyright" %}
    {{ siteCopyright|safe }}
</div>

Handle Markdown format content

AnQiCMS also supports Markdown editor.When you use Markdown format to write articles in the background, the system will convert them to HTML code.When outputting such content in the template, you need to ensure the following two points:

  1. Markdown to HTML:If the Markdown editor is enabled in the background "Global Settings" -> "Content Settings" orarchiveDetailspecified explicitly in the tagrender=true(such as{% archiveDetail with name="Content" render=true %}),AnQiCMS will convert Markdown text to HTML before outputting.
  2. HTML safe rendering:The converted HTML still needs to be used.|safeThe filter must be applied to render correctly.

Therefore, even if the content is written in Markdown, it is recommended to add it when outputting to the template.|safeFilter:

{# 输出Markdown转换后的文章内容,并安全渲染HTML #}
<div>
    {% archiveDetail articleContent with name="Content" render=true %}
    {{ articleContent|safe }}
</div>

render=trueEnsure Markdown is converted to HTML, while|safethen these HTML are allowed to be normally parsed by the browser.

When not to use|safefilter (or use|escape)

Though|safeThe filter is very convenient when displaying rich content, but please remember the security implications behind it.|safeIt tells the system “This content is safe, please trust it.” Therefore,Absolutely cannot pass content from untrusted sources (such as user submitted comments, messages, or any unsterilized inputs) directly through|safeFilter outputThis will directly expose the risk of XSS attacks, malicious users may insert JavaScript code, steal user information, modify page content, and even hijack sessions.

If you really need to display HTML tags as plain text (for example, in a code example) or to ensure that any existing HTML tags are escaped, you can rely on AnQiCMS's default automatic escaping behavior, that is, not using|safe. If you need to explicitly escape, you can use|escapeFilter:

{# 显示HTML标签作为文本,而不是渲染它 #}
<pre>
    {% archiveDetail codeSnippet with name="SomeHtmlCodeField" %}
    {{ codeSnippet|escape }}
</pre>

Here|escapeThe filter will force HTML special characters to be escaped to ensure they are displayed as literal text.

Summary

AnQiCMS's template mechanism provides a basic security protection through default HTML escaping. When you need to render confirmed-safe content with HTML tags, please use|safeFilter. But when handling any content from users or other untrusted sources, always be cautious, ensuring that the content is strictly sanitized and validated on the server side to avoid potential security vulnerabilities.Correctly understand and apply|safeThe filter is the key to ensuring the integrity and content security of the AnQiCMS website.


Frequently Asked Questions (FAQ)

1. Why did my article's main content show up?<p>/<strong>Are HTML tags, rather than the rendered effect?This is usually because you used it directly in the template{{ 变量名 }}The method of outputting the article content, while the AnQiCMS template engine, for security reasons, defaults to escaping HTML special characters. To correctly render HTML tags, you need to use|safeFilter, for example{{ archive.Content|safe }}.

2. The content I get from user comments can be used directly|safeAre the filter outputs?It is strongly recommended not to use directly|safeThe filter outputs unprocessed user comments. User comments may contain malicious HTML tags or JavaScript code, which, if output directly, could cause cross-site scripting (XSS) risks.Before outputting any user-generated content, it is imperative to perform strict server-side data cleaning, filtering, and sterilization, removing all untrusted HTML tags and attributes.Even after purification, it should be carefully considered whether to use it based on specific security policies|safe.

3. Markdown formatted article, if the Markdown editor is enabled on the back end, it still needs to be used|safe?Yes, it still needs to be used|safe. Even if the Markdown editor is enabled on the backend, the system will convert it to HTML, but the template engine will still follow the default escaping rules when outputting these HTMLs.Therefore, to ensure that the converted HTML can be correctly rendered by the browser, you still need to use it in the template.|safeFilter, for example{{ articleContent|safe }}.

Related articles

How to alternate different CSS classes or styles while looping through list items?

In web design, to enhance visual aesthetics and user experience, we often encounter situations where we need to alternate different CSS classes or styles for list items (such as article lists, product lists, navigation menus, etc.).For example, make the background color of odd and even rows different, or apply a unique layout style every few items.AnQiCMS (AnQiCMS) leverages its flexible template engine to provide a variety of simple and efficient methods to meet this requirement.

2025-11-08

How to display the default prompt information when the article list obtained through `archiveList` is empty?

When using Anqi CMS to build a website, we often need to display lists of articles, products, or other content.These lists are usually dynamically retrieved and rendered using such template tags as `archiveList`.}However, if a list is empty for various reasons (such as temporarily no content under a category, or empty search results), the user experience will be greatly reduced if the page is just empty.

2025-11-08

How to implement reverse or custom sorting output of AnQiCMS's `for` loop?

The order of website content listings is crucial for user experience and information delivery.Whether it is news updates, product displays, or article archives, flexibly controlling the output order of lists is a common demand in website operation.AnQiCMS provides a powerful and easy-to-use template engine, allowing us to easily control the arrangement of lists, including reverse order and sorting by specific rules.### AnQiCMS Template Engine Basics The AnQiCMS template system adopts the syntax style of the Django template engine, using concise tags and variable declarations

2025-11-08

How to get the current loop item index or remaining item count in an article?

When using AnQi CMS for website content display, we often need to finely control each item in the list.This may include adding numbers to articles, highlighting the first or last item in a list, or applying different styles based on the position of the item in the list.The AnQi CMS template system uses a syntax similar to the Django template engine, where the key to handling list loops is the `for` loop tag.

2025-11-08

How to use the `include` tag to reuse header, footer, and other common code segments in AnQiCMS templates?

Building website templates in AnQiCMS, efficient code reuse is the key to improving development speed and maintenance efficiency.Imagine, the header (Header) and footer (Footer) of a website appear almost on every page. If the same code is written on each page, it is not only time-consuming, but also, once a modification is needed, it has to be searched and updated on each page, which is undoubtedly a huge amount of work.

2025-11-08

How to pass specific variables or data when including a sub-template?

Advanced AnQiCMS Template: `include` Sub-template Data Passing Techniques and Practices In AnQiCMS template development, the `include` tag is undoubtedly a powerful tool for enhancing template reusability and modularization.It allows us to extract common code snippets (such as page headers, footers, sidebars, etc.) and then introduce them where needed, thus avoiding repetition and making the template structure clearer and maintenance more efficient.However, the sub-templates introduced often need to display different content, which raises a core question: how to introduce sub-templates at the time

2025-11-08

How does the `macro` function in AnQiCMS templates help me reduce redundant rendering logic?

In Anqi CMS template development, improving efficiency and maintaining code cleanliness is the goal that every developer is pursuing.web pages often contain many structurally similar but content-wise different areas, such as each article card in the article list, the various features of a product detail page, or each link item in the navigation menu.If each time you have to rewrite this similar rendering logic, it not only takes time and effort, but also, once you need to make modifications, you may face the dilemma of having to make repetitive changes in multiple places.Luckyly, AnQiCMS's powerful template system provides `macro` macro function

2025-11-08

What role does the `extends` tag play in the AnQiCMS template inheritance system?

In AnQiCMS template development, the `extends` tag plays a core role, it is the key to building efficient, maintainable and structurally unified website templates.The `extends` tag can be understood as creating a bridge between 'master' and 'child pages', allowing you to easily define a common layout skeleton for the entire website without repeating a lot of the same code on each page.

2025-11-08