In the template development process of AnQi CMS, handling single quotes, double quotes, and other special characters in content is a common requirement, especially in ensuring the correct display of the page and preventing security issues.The template engine of Anqi CMS (similar to Django syntax) provides a set of intelligent and secure mechanisms when handling these characters, allowing us to flexibly control the display of content.
The default behavior of the template: security 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, for example,{{ archive.Title }}or{{ system.SiteName }}The template engine will automatically escape the content to HTML.
The purpose of this automatic escaping is to prevent cross-site scripting (XSS) attacks and avoid special characters in the content (such as</>/&/"/')Destroys the HTML structure of the page. For example:
- If your article title 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. - Double quotes
"will be escaped as". - Single quotes
'will be escaped as'. &Symbols will be escaped as&.
This default escaping behavior is very useful in most cases, it ensures that the text content we retrieve from the database, whether it is a title, introduction, or other plain text field, can be displayed safely on the web page without causing layout chaos or security vulnerabilities.
When is it necessary to explicitly unescape: usesafeFilter
However, in certain specific scenarios, we may need to output the "original" content containing HTML tags, such as the detailed content of articles, or the图文排版 edited through a rich text editor. If these contents are also escaped, then all<p>/<img>/<strong>All tags will be displayed as plain text, rather than being parsed by the browser as corresponding styles and structures.
At this time, it is necessary to use the templates provided by the Anqi CMS.safeThe filter explicitly tells the template engine that this content is "safe" and does not need to be HTML-escaped. The usage is very simple, just add it after the variable you need to output.|safeas follows:
{# 假设archive.Content是从富文本编辑器获取的文章内容,包含HTML标签 #}
<div>
{{ archive.Content|safe }}
</div>
{# 如果是普通的纯文本,通常不需要|safe,但如果确定其中有需要解析的HTML,也可以用 #}
<p>{{ category.Description|safe }}</p>
It should be particularly noted that usingsafebe cautious when using the filter.Only use it when you are sure that this content has been strictly filtered and verified, and will not contain any malicious scripts or destructive HTML code. If the content comes from unverified user input, use it directly.safeMay pose XSS security risks.
Quotation handling in specific scenarios:addslashesandescapejsFilter
In addition to the conventional HTML escaping, we may sometimes encounter situations where we need to dynamically concatenate strings in JavaScript code, or we need to include special characters in HTML attribute values. At this point,addslashesandescapejsThe filter comes into play.
addslashesFilter: Add backslash to predefined charactersThis filter is mainly used for single quotes ('), double quote ()"), backslash (\)and NULL character is preceded by a backslash.It is very useful when building JavaScript strings, JSON strings, or certain specific code structures that require these escape characters.For example, if you need to construct a JavaScript variable in a template, its value contains quotes:
<script> var message = "{{ system.SiteName|addslashes }}"; alert(message); </script>If
system.SiteNameThe 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 (such as newline characters, quotes, backslashes, etc.) in strings to JavaScript-safe Unicode escape sequences (\uxxxx),ensure that the string can be safely embedded into JavaScript code. It is more comprehensive in handling JavaScript string security issues.addslashes更全面地处理JavaScript字符串安全问题。<script> var description = "{{ archive.Description|escapejs }}"; console.log(description); </script>If
archive.DescriptionContaining multiline text or special characters,escapejsit will convert it into a single-line and safe JavaScript string.
Local control:autoescapetags
If you need to control the automatic escaping behavior of content in a certain area of a template file uniformly, rather than adding it to each variable one by one|safeFilters can be usedautoescapeLabel.
{% autoescape off %}:在这个标签块内的所有变量输出将will not自动转义。{% autoescape on %}:在这个标签块内的所有变量输出将will自动转义(这也是默认行为,所以通常用于重新开启之前关闭的自动转义)。
{# 默认情况下自动转义是开启的 #}
<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 %}
通常,推荐的做法是保持默认的自动转义行为,只在确实需要输出HTML内容的特定字段上使用English|safeFilter, this can ensure the maximum security of the website.
In general, when dealing with single quotes, double quotes and other special characters in templates, the safeCMS uses the default HTML auto-escape,safeFilter,addslashesandescapejsFilter as well asautoescapeLabel, provides powerful and flexible control means. Understanding and using these mechanisms properly can help us build both beautiful and safe websites.
Common Questions (FAQ)
Q1: In the 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 page structure damage.|escapeThe filter enforces this escaping, but since the default behavior is already to escape, it is usually not necessary to add an|escapeIt will not change its output. It is more for explicitly indicating that "I want this content to be escaped".
while|safeThe filter works exactly the opposite, it is used forExplicitly cancelingDefault HTML escaping. When you use|safeWhen you do this, you are telling the template engine that this content is “safe”, and the HTML tags within it should be parsed and displayed normally by the browser, rather than being escaped into plain text. Therefore, they are two filters used for different purposes:|escapeIs to strengthen or confirm the escape (although it is usually not necessary),|safeIs to cancel the escape.
Q2: Why does my article detail content (edited through the rich text editor) display as plain text with tags such as<p>/<strong>on the page instead of formatted effects?
This is because of the default HTML escaping behavior of 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.<p>Transcoded into<p>,<strong>Transcoded into<strong>etc. To ensure that these HTML tags are correctly parsed and displayed with formatting by the browser, you need to use|safeFilter. For example, on the article detail page, you will usually see something like{{ archive.Content|safe }}such writing. Please make surearchive.Contentit is content you trust and verified.
Q3: I tried to dynamically generate a segment of JavaScript code in the template, which includes variable values, but found a syntax error in JavaScript. Is this related to the handling of quotes?
It is very likely related.JavaScript strings and HTML attribute escaping rules are different from plain HTML text."to escape as")May cause JavaScript syntax errors, or worse, introduce JavaScript injection vulnerabilities.
In this case, you should use|escapejsFilter.|escapejsWill escape the variable content into a JavaScript compatible format (for example, escaping'to escape as\u0027,"to escape as\u0022), ensuring it is safe to