During the template development process of AnQi CMS, handling single quotes, double quotes, and other special characters in the content is a common requirement, especially in ensuring the correct display of the page and preventing security issues.The Anqi CMS template engine (similar to Django syntax) provides a smart and secure mechanism when handling these characters, allowing us to flexibly control the display of content.
Default behavior of the template: safety first
Firstly, we need to understand one of the core design concepts of the Anqi CMS template:Security first. This means that when you output variables directly in the template, such as{{ archive.Title }}or{{ system.SiteName }}This template engine automatically escapes the content.
The purpose of this automatic escaping is to prevent cross-site scripting (XSS) attacks and avoid special characters in the content such as</>/&/"/') Destroy the HTML structure of the page. For example:
- If the title of your article contains
<script>alert('XSS')</script>, it will be escaped as<script>alert('XSS')</script>, it will only be displayed as plain text in the browser and will not execute malicious scripts. - Quotation marks
"Will be escaped to". - single quote
'Will be escaped to'. &symbols are escaped as&.
This default escaping behavior is very useful in most cases, it ensures that the text content we extract from the database, whether it is a title, summary, or other plain text field, can be safely displayed on the web page without causing layout errors or security vulnerabilities.
When do you need to explicitly unescape: usesafeFilter
However, in certain specific scenarios, we may need to output the "raw" content containing HTML tags, such as the detailed content of articles, or the图文排版 edited by rich text editors. If these contents are also escaped, then all the<p>/<img>/<strong>Tags will be displayed as plain text, rather than being parsed by the browser as corresponding styles and structures.
At this point, it is necessary to use the template provided by Anqi CMS.safeThe filter explicitly tells the template engine that this content is 'safe' and does not require HTML escaping. The usage is very simple, just add it after the variable that needs to be output.|safeand it is done:
{# 假设archive.Content是从富文本编辑器获取的文章内容,包含HTML标签 #}
<div>
{{ archive.Content|safe }}
</div>
{# 如果是普通的纯文本,通常不需要|safe,但如果确定其中有需要解析的HTML,也可以用 #}
<p>{{ category.Description|safe }}</p>
It should be noted thatsafeextreme caution must be taken when using a filter.Only when you are sure that this content has been strictly filtered and verified and does not contain any malicious scripts or destructive HTML code should you use it. If the content comes from unverified user input, use it directly.safeMay lead to XSS security risk.
Quotation handling in specific scenarios:addslashesandescapejsFilter
In addition to the usual HTML escaping, sometimes we may encounter situations where we need to dynamically concatenate strings in JavaScript code or include special characters in HTML attribute values. At this point,addslashesandescapejsThe filter comes into play.
addslashesFilter: Add backslashes for predefined charactersThis filter is mainly used to add backslashes in single quotes ('Punctuation marks (and) quotation marks ("), backslash (\Backslashes are added before the NULL character. It is very useful when building JavaScript strings, JSON strings, or certain specific code structures.For example, if you need to build a JavaScript variable in a template that includes quotes:
<script> var message = "{{ system.SiteName|addslashes }}"; alert(message); </script>If
system.SiteNamehas a value ofAnQi's CMSAfteraddslashesAfter processing, it will become in JavaScript:AnQi\'s CMSEnsure the correctness of the string.escapejsFilter: JavaScript code escapingescapejsThe filter will convert special characters in strings (such as newline characters, quotes, backslashes, etc.) to JavaScript-safe Unicode escape sequences (\uxxxxEnsure that the string can be safely embedded in JavaScript code. It is more comprehensive in handling JavaScript string security issues.addslashesIt handles JavaScript string security issues more comprehensively.<script> var description = "{{ archive.Description|escapejs }}"; console.log(description); </script>If
archive.DescriptionContains multi-line text or special characters,escapejsIt will convert it into a single-line and safe JavaScript string.
Local control:autoescapeTag
If you need to control the automatic escaping of content in a certain area of a template file, rather than adding it to each variable individually|safeFilters can be usedautoescape.
{% autoescape off %}All variables output within this label block will bewon'tautomatically escaped.{% autoescape on %}All variables output within this label block will bewillAutomatically escaped (this is also the default behavior, so it is usually used to re-enable automatic escaping that was previously disabled).
{# 默认情况下自动转义是开启的 #}
<p>这是默认转义:{{ some_text_with_html_tags }}</p>
{% autoescape off %}
{# 在这个块内,变量将不会自动转义 #}
<p>这里的内容不会自动转义:{{ trusted_html_content }}</p>
<p>这个也是:{{ another_html_snippet }}</p>
{% endautoescape %}
{% autoescape on %}
{# 重新开启自动转义,或者用于嵌套块 #}
<p>回到自动转义:{{ more_text }}</p>
{% endautoescape %}
The recommended practice is to maintain the default automatic escaping behavior, only using it for specific fields where HTML content needs to be output|safeA filter, which can ensure the security of the website to the greatest extent possible.
In general, Anqi CMS handles single quotes, double quotes, and other special characters in templates by default HTML automatic escaping,safeFilter,addslashesandescapejsas well as filtersautoescapeTags provide powerful and flexible control means. Understanding and properly utilizing these mechanisms can help us build websites that are both beautiful and safe.
Frequently Asked Questions (FAQ)
Q1: In Anqi CMS template,|safeand|escapeWhat are the differences between filters?
The template engine of AnQi CMS defaults to escaping all output variable content to prevent XSS attacks and破坏页面结构 from being broken.|escapeThe filter enforces this escaping, but since the default behavior is already escaping, it is usually the case that you add a variable to|escapeIt will not change its output. It is more used to explicitly indicate that 'I want this content to be escaped'.
And|safeThe filter is exactly the opposite, it is used toExplicitly cancelDefault HTML encoding. When you use|safeWhen, you are telling the template engine that this content is "safe", the HTML tags it contains should be normally parsed and displayed by the browser, rather than being escaped into plain text. Therefore, they are used to achieve different purposes and are two filters for different purposes:|escapeIs a reinforcement or confirmation of escaping (although usually not necessary),|safeIs to unescape.
Q2: Why does my article detail content (edited through a rich text editor) display on the page as plain text with tags such as<p>/<strong>instead of formatted effects?
This is because of the default HTML escaping behavior of the Anqi CMS template. The content generated by the rich text editor includes HTML tags, and for safety, the template engine escapes these contents when outputting them.<p>Escaped became<p>,<strong>Escaped became<strong>Etc. To make these HTML tags be parsed and displayed in the correct layout by the browser, you need to use the article content field output with|safeFilter. For example, you will often see something similar on the article detail page{{ archive.Content|safe }}Such formatting. Please make surearchive.ContentIt is the content you trust and has been verified.
Q3: I tried to dynamically generate a JavaScript code snippet in a template that includes variable values, but I found a JavaScript syntax error, is this related to quote handling?
It is likely related. JavaScript strings and HTML attributes have different escaping rules for quotes and special characters than plain HTML text.If you directly embed a template variable that may contain quotes or special characters into a JavaScript string, the default HTML escaping (such as"Escape as"It could lead to JavaScript syntax errors, or worse, introduce a JavaScript injection vulnerability.
In this case, you should use|escapejsfilter.|escapejsEscape the variable content to a JavaScript-compatible format (for example, to'Escape as\u0027, will"Escape as\u0022), ensuring it is safely