When building website templates with AnQiCMS, we often encounter various template tags and filters. Among them,addslashesthe filter is followed by|safeThis combination of filters appears repeatedly in some document examples, which may confuse some new users: why do you need to add a backslash first, and then immediately declare the content as 'safe', without escaping it?This actually has clever design and important security considerations.

To understand the intention of this combination, we need to understand separatelyaddslashesand|safeThe specific role of these filters in the AnQiCMS template engine.

addslashesThe role of the filter

addslashesIts name implies that its function is to use specific predefined characters in a string (mainly single quotes)', double quotes"and backslash\A backslash is added before. The main purpose of this operation is to 'escape' these special characters so that they are not damaged when processed by other parsers, and do not cause unexpected behaviors.

For example, let's say you have a string安企"CMS"If directly output to an environment that strictly parses quotes (such as a JavaScript code string literal or an HTML element attribute value), the double quotes in the middle may be incorrectly considered as the end of the string, resulting in a syntax error. Afteraddslashesprocessed, it will become安企\"CMS\".

In traditional web development,addslashesCommonly used to process user input data before inserting it into a database query statement to prevent SQL injection and other security issues. But in the context of AnQiCMS templates, its usage is broader, especially when it is necessary to safely embed variable content outside of HTML, such as JavaScript scripts or HTML elements.data-*property is in.

|safeThe role of the filter

AnQiCMS template engine (similar to Django template engine) to ensure website security, it defaults to escaping all variable content output to the page. This means that if your variable contains</>/&/"/'Characters that are special in HTML are automatically converted to their corresponding HTML entities (for example<Will become&lt;To avoid the execution of malicious HTML code or JavaScript scripts on the page, and effectively prevent cross-site scripting attacks (XSS).

And|safeThe filter's role is to explicitly tell the template engine: 'This content is safe, please do not escape it as HTML, and output it directly as a raw string.'This is usually used for strings that you are sure are pure HTML code, or have been safely processed by other means.

WhyaddslashesFollowing that.|safe?

Now, let's combine these two filters to see whenaddslashesAfter processing a string, such as安企"CMS"becomes安企\"CMS\"If there is a lack of|safehow will the template engine handle it?

If安企\"CMS\"Directly output to HTML without|safeThe template engine will interpret the backslashes within it\Treated as a common character, and may attempt to escape it as HTML (although the backslash itself is not always escaped in HTML, in some HTML attributes or specific contexts, its behavior may not be as expected, or at least, the template engine will treat it as plain text rather than as instructions). Moreover, it may break the use ofaddslashesThe original intention.

The most common application scenario for this combination is to embed the value of the template variable into the JavaScript attribute of an HTML element, for exampledata-*Attribute, or use directly as<script>JavaScript variable within the tag.

For example, we want to change the name of a productAnQi's ProductPass to a JavaScript function or store in adata-product-namethe attribute:

  1. Noneaddslasheswithout|safe: data-product-name="{{ product.name }}"Ifproduct.nameIsAnQi's Product, the output might becomedata-product-name="AnQi&#39;s Product". Although safe, JavaScript reads thisdataWhen the attribute is obtained, it will be an HTML entity and needs to be decoded additionally.

  2. Onlyaddslashes, there is no|safe: data-product-name="{{ product.name|addslashes }}"Ifproduct.nameIsAnQi's Product,addslasheswill make it becomeAnQi\'s Product. But at this time, the template engine will default to\and'Escape characters for HTML, the final output may becomedata-product-name="AnQi&bsol;&#39;s Product"The escape form of backslash may vary depending on the engine and context, but it is definitely not what you want\Character), this will break the structure of JavaScript string literals.

  3. At the same timeaddslashes | safe: data-product-name="{{ product.name|addslashes|safe }}"Ifproduct.nameIsAnQi's Product,addslashesAfter processing isAnQi\'s Product. Then|safeTell the template engine: "This content has been processed, the backslashes are intentional, please output it as is. The final HTML output will be"data-product-name="AnQi\'s Product".

When JavaScript code readsdata-product-nameit correctly parses the string containing escaped backslashesAnQi\'s Product. Since JavaScript itself handles the escaping of backslashes in string literals, the string obtained in JS isAnQi's ProductThis perfectly preserves the original data and does not introduce any additional HTML escape entities at the HTML level, avoiding the trouble of double decoding.

Summary

addslashes | safeThe intention of this combination is to:

  • Prepare a string for non-HTML context: addslashesResponsible for escaping quotes and backslashes in strings to safely embed them in contexts requiring such escaping rules (such as JavaScript string literals, JSON data, or certain data attributes).
  • Prevent unnecessary HTML escaping: |safeIt isaddslashesAfter completing the task, inform the AnQiCMS template engine that this content contains escape characters (backslashes) required for a specific context and should not be HTML-escaped by the template engine. This ensuresaddslashesThe backslash can be correctly identified and processed by the target parser (such as a JavaScript interpreter), rather than being misunderstood or additionally escaped by the HTML parser.

In short, it coordinates between different levels of escaping to ensure that the data is both secure and maintains the integrity and correctness of the content when passed from the server-side through the template to the front-end script.


Frequently Asked Questions (FAQ)

  1. When should I useaddslashes | safethe combination?This combination is mainly suitable for when you need to embed the variable content of the AnQiCMS template as a string in the JavaScript code within the HTML (for example, defining JS variablesvar myVar = '{{ some_data|addslashes|safe }}';)or HTML elements'data-*This ensures that special characters (especially quotes and backslashes) in the string are correctly escaped, thus avoiding JavaScript syntax errors or data parsing issues, and also avoiding the interference of HTML's default escaping with these backslashes.

  2. Use|safeWill it introduce XSS security risks?Yes,|safeThe filter will disable the default HTML escaping mechanism of AnQiCMS template engine. This means that if you use|safeThe content is from untrusted user input, and it contains malicious HTML tags or JavaScript code. This content will not be escaped and will be output directly to the page, which may lead to XSS attacks. Therefore, when using|safeAt that time, you must ensure that the content you handle is completely trustworthy, or it has been strictly validated and cleaned up.

  3. If my string itself contains HTML tags, I want it to be parsed as HTML and also need to useaddslashes?If the string is itself a valid HTML code and you want it to be parsed and displayed on the page, then you usually just need to use|safeFilter, without needingaddslashesFor example, the main content of the article is usually in HTML format, directly{{ article.content|safe }}