When building website templates with AnQiCMS, we often encounter various template tags and filters. Among them,addslashesfilters are 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 is actually a clever design and important security considerations.
To understand the intention of this combination, we need to understand separatelyaddslashesand|safethe specific role of these two filters in the AnQiCMS template engine.
addslashesThe role of the filter
addslashesAs the name implies, its function is to specify a predefined character (mainly the single quote) in a string', double quotes)"and the backslash\Add a backslash at the beginning.The main purpose of this operation is to 'escape' these special characters, so that they do not disrupt the structure of the original content or cause unexpected behavior when processed by other parsers.
For example, suppose you have a string安企"CMS"If directly output to an environment that requires strict parsing of quotes (such as string literals in JavaScript code or the value of an HTML element attribute), the double quotes in the middle may be mistakenly considered as the end of the string, resulting in syntax errors.addslashesAfter processing, it will become安企\"CMS\".
In traditional web development,addslashesFrequent in processing user input data before inserting it into database query statements to prevent SQL injection and other security issues. But in the template context of AnQiCMS, its usage is broader, especially when it is necessary to safely embed variable content outside of HTML, such as in JavaScript scripts or HTML elements.data-*[en] Attribute is in place.
|safeThe role of the filter
AnQiCMS's 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</>/&/"/'Special HTML characters, they are automatically converted to their corresponding HTML entities (for example<Will become<To avoid malicious HTML code or JavaScript scripts from executing on the page, it effectively prevents cross-site scripting (XSS) attacks.
while|safeThe function of the filter is to explicitly tell the template engine: 'This content is safe, please do not escape it as HTML, and output it directly as the original string.'This is usually used for strings that you are sure are pure HTML code, or have been processed by other security measures.
Whyaddslashesis usually followed by|safe?
Now, let's combine these two filters and see.addslashesAfter processing a string, such as converting安企"CMS"becomes安企\"CMS\"if there is a lack of|safe, how will the template engine handle it?
If安企\"CMS\"output directly to HTML without|safethe template engine will interpret the backslashes in it\treated as plain characters, and may attempt to HTML-escape them (although the backslash itself is not always HTML-escaped, in certain HTML attributes or specific contexts, its behavior may not be as expected, or at least, the template engine may treat it as plain text rather than as a directive). More importantly, it may break the use ofaddslashesThe original intent.
The most common application scenario for this combination is to embed the value of template variables into JavaScript properties of HTML elements, such asdata-*Property, or directly as<script>JavaScript variables inside the tag.
For example, we want to name a productAnQi's ProductPassed to a JavaScript function, or stored in adata-product-namethe attribute:
none
addslashesand does not have|safe:data-product-name="{{ product.name }}"Ifproduct.nameYesAnQi's Product, the output may becomedata-product-name="AnQi's Product". Although secure, JavaScript when reading thisdataWhen an attribute is, the result will be an HTML entity, which needs to be decoded additionally.Only
addslashes, no|safe:data-product-name="{{ product.name|addslashes }}"Ifproduct.nameYesAnQi's Product,addslasheswill make it becomeAnQi\'s Product. But at this point, the template engine will default to\and'HTML escaping, the final output may becomedata-product-name="AnQi\'s Product"The escaped form of backslashes may vary depending on the engine and context, but it is definitely not what you want\This character (comma), however, can break the structure of JavaScript string literals.Used simultaneously
addslashes | safe:data-product-name="{{ product.name|addslashes|safe }}"Ifproduct.nameYesAnQi's Product,addslashesAfter processing isAnQi\'s Product.|safeTell the template engine: "This content has been processed, the backslashes are intentional, and they should be output as is." The final HTML output will bedata-product-name="AnQi\'s Product".
When JavaScript code readsdata-product-namea property, it will correctly parse it as a string containing escaped backslashesAnQi\'s ProductThe JavaScript language itself handles escaping of backslashes in string literals, so the string obtained in JS isAnQi's ProductRetains the original data perfectly, and does not introduce any additional HTML escape entities at the HTML level, avoiding the trouble of secondary decoding.
Summary
addslashes | safeThe intention of this combination is:
- Prepare a string for non-HTML context use:
addslashesMainly responsible for escaping quotes and backslashes in strings to make them safe to be embedded in contexts requiring this escaping rule (such as JavaScript string literals, JSON data, or certain data attributes). - Prevent unnecessary HTML escaping:
|safeis inaddslashesAfter completing the work, inform AnQiCMS template engine that this content contains escape characters (backslashes) required for specific context. It should not be HTML-escaped by the template engine. This ensuresaddslashesThe generated backslashes 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 brief, it is about coordinating 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.
Common Questions and Answers (FAQ)
When should I use
addslashes | safecombination?This combination is mainly suitable for when you need to embed variable content from AnQiCMS templates as a string into JavaScript code (e.g., defining JS variablesvar myVar = '{{ some_data|addslashes|safe }}';)or an HTML elementdata-*At the time of the attribute.This ensures that special characters (especially quotes and backslashes) within the string are correctly escaped, thus avoiding JavaScript syntax errors or data parsing issues, while also avoiding interference from HTML's default escaping of these backslashes.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 may contain 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|safeWhen, you must ensure that the content being processed is completely trustworthy, or has been strictly validated and cleaned.If my string already contains HTML tags, I want it to be parsed as HTML and also to be enclosed in quotes.
addslashes?If your string is already a valid HTML code and you want it to be parsed and displayed by the browser on the page, then you usually just need to use|safeFilter, without needingaddslashes. For example, the article body is usually in HTML format, directly{{ article.content|safe }}