In website content management, especially when we want to insert dynamic data into JavaScript code or build JSON-formatted output, handling special characters is a crucial aspect that cannot be ignored. The template engine of AnQiCMS (AnQiCMS) provides a rich set of filters to help us elegantly handle such issues, among whichaddslashesThe filter is a practical tool specifically designed for this kind of scenario.

addslashesThe function of the filter is to parse.

addslashesFilter, as the name implies, its core function is to add a backslash before a specific character in a string. In the programming world, these "specific characters" are often those that have special meanings in some grammatical environments, such as single quotes ("'), double quote ()") and the backslash (\)\).

addslashesThe filter is born to solve this kind of problem.It scans the target string and automatically adds a backslash before any single quotes, double quotes, or backslash characters that appear, "escaping" them into ordinary characters to avoid confusion with the delimiters in JavaScript or JSON syntax.

Application in JavaScript

When we need to dynamically fill the data obtained from the backend into the front-end JavaScript variables or function parameters in the AnQiCMS template,addslashesThe filter is particularly important.

For example, we may have a user comment content that includes various special characters. If we directly assign this content to a JavaScript variable:

<script>
    var comment = "{{ archive.Content }}"; // 假设archive.Content是用户评论内容
    alert(comment);
</script>

Ifarchive.ContentThe value of用户说:"今天的AnQiCMS真好用!"Then the generated JavaScript code will be:

<script>
    var comment = "用户说:"今天的AnQiCMS真好用!"";
    alert(comment);
</script>

Clearly,今天的AnQiCMS真好用!The double quotes will end the string prematurely, causing the subsequent JavaScript code to have a syntax error.

At this point, useaddslashesThe filter can effectively solve this problem:

<script>
    var comment = "{{ archive.Content|addslashes }}";
    alert(comment);
</script>

AfteraddslashesAfter processing, ifarchive.ContentYes用户说:"今天的AnQiCMS真好用!"The output JavaScript code will become:

<script>
    var comment = "用户说:\"今天的AnQiCMS真好用!\"";
    alert(comment);
</script>

This is,commentVariable can correctly receive complete strings containing double quotes, ensuring the correct execution of JavaScript code and the normal operation of the page.

In the Application of JSON Data Output

JSON (JavaScript Object Notation) is a lightweight data interchange format, widely used in front-end and back-end data transmission.JSON has strict requirements for the format of strings, especially double quotes and backslash characters.A double quote or backslash that is not properly escaped can cause the JSON data structure to be destroyed, leading to front-end parsing failure.

When outputting JSON data through the AnQiCMS template, for example,<script type="application/json">Label embedded data, or as the response body of an AJAX request,addslashesThe filter ensures that the generated JSON string conforms to the standard.

假设我们有一个包含多媒体信息的AnQiCMS文章对象,需要将其部分数据以JSON格式传递给前端:

<script type="application/json" id="article-data">
{
    "title": "{{ archive.Title|addslashes }}",
    "description": "{{ archive.Description|addslashes }}",
    "content": "{{ archive.Content|addslashes }}"
}
</script>

Here,archive.Title/archive.Descriptionandarchive.ContentMay contain various special characters from user input.addslashesWill ensure that the double quotes and backslashes in these strings are correctly escaped to avoid invalid JSON structure.

For example,archive.DescriptionYes一个关于"CMS"系统的介绍afteraddslashesProcessed, it will become in JSON"description": "一个关于\"CMS\"系统的介绍"Instead of destroying the structure,"description": "一个关于"CMS"系统的介绍".

Combine|safe[en]The use of filters

In AnQiCMS template engine, the default behavior is to encode all outputs as HTML entities to prevent XSS attacks. This means that ifaddslashesthe filter outputs\",Template engine may encode it again.&quot;. This double encoding is incorrect for JavaScript or JSON.

To solve this problem, it is usually necessary to useaddslashes之后,紧接着使用|safeFilter.|safeThe filter tells the template engine that the output has been manually processed and is safe, so no further HTML entity encoding is needed.

The correct usage is usually:

<script>
    var myString = "{{ some_variable|addslashes|safe }}";
</script>

or used in JSON:

<script type="application/json">
{
    "key": "{{ some_variable|addslashes|safe }}"
}
</script>

This is,addslashesensures the safety of strings at the JavaScript/JSON grammatical level, and|safethen ensures theaddslashesThe output is not unnecessarily encoded with HTML, thus generating correct JavaScript or JSON code on the final page.

Summary

addslashes|safeFilter usage, ensuring data is presented in the most accurate and safest way under complex scenarios.


Common Questions (FAQ)

  1. addslashesandescapejsWhat are the differences between filters? addslashesMainly for escaping single quotes, double quotes, and backslashes, so that they do not cause syntax errors in JavaScript strings or JSON.escapejsIt is a more comprehensive JavaScript string literal escaping tool, it not only handlesaddslashesin addition to the characters being processed, it will also handle newline characters, carriage returns, tab characters, and other special characters (such as</>/&、non-ASCII characters, etc.) are escaped, ensuring they can be safely used in JavaScript strings. For general embedding of JavaScript strings,escapejsIt is usually a more stable choice; but if you only need to handle quotes and backslashes,addslashesit is more direct.

  2. Why do you need to addaddslashesoften needing to be added after|safe?This is because AnQiCMS's template engine defaults to automatically escaping HTML to prevent cross-site scripting (XSS) attacks.addslashesAfter the filter has processed the string, for example,'Changes to\'。If this is not added at this time|safe,the template engine may encode it\'of'to HTML entities again, becoming&#39;,which will cause the JavaScript or JSON parsing to fail.|safeThe filter tells the template engine that the current content has been processed and does not need to be encoded as HTML entities, thus preservingaddslashesthe expected escaped result.

  3. If my JSON or JavaScript data itself contains HTML tags,addslasheswill it handle them? addslashesThe filter will not specifically handle HTML tags.Its responsibility is to escape special characters that affect JavaScript or JSON syntax (single quotes, double quotes, backslashes).innerHTML), then inaddslashesProcessed, you may also need to consider other HTML escape mechanisms to ensure overall safety, but this is usually an operation on the JavaScript level, not during template output of JSON/JS data byaddslashesDirectly complete. If the special characters (such as quotes in attributes) carried by the HTML tag itself need to be escaped,addslashesit will handle these quotes but will not change the structure of the HTML tag.