In AnQiCMS templates, handling dynamic content and safely embedding it into JSON strings is a common requirement, especially when it is necessary to pass backend data to frontend JavaScript. In such scenarios, many users would naturally think of usingaddslashesThis filter is used to process special characters. So,addslashesCan this filter help in this aspect? Let's delve into it.

AnQiCMS template and dynamic content

AnQiCMS uses a syntax similar to the Django template engine, allowing through{{变量}}to output dynamic data, or through{% 标签 %}to call more complex logic and data, such as{% archiveDetail with name="Title" %}Get the document title, or{% system with name="SiteName" %}Retrieve website name. This dynamically obtained content may contain various characters, including plain text, HTML tags, special symbols, and even quotes and backslashes.

addslashesThe role of the filter

According to the AnQiCMS documentation,addslashesThe filter is mainly used to add a backslash before specific predefined characters in a string. These predefined characters include: single quotes ('Punctuation marks (and) quotation marks (") and backslash (\It is mainly used to escape these specific characters to avoid syntax errors or security issues in certain string processing scenarios (such as inserting into SQL queries or JS string literals).

For example, if you have a stringThis is a "test" with a 'single quote' and a backslash \.Afteraddslashesit may becomeThis is a \"test\" with a \'single quote\' and a backslash \\.This filter is usually used with|safeto ensure that it is not doubly escaped when output to HTML

when the content encounters a JSON string

JSON (JavaScript Object Notation) is a lightweight data interchange format, which has strict requirements for the format of strings. In JSON, strings must be enclosed in double quotes, and some special characters within the string must also be escaped, for example:

  • Quotation marks"Must be escaped as\"
  • backslash\Must be escaped as\\
  • Carriage return\nMust be escaped as\\n
  • Line feed\rMust be escaped as\\r
  • Tab\tMust be escaped as\\t
  • Other control characters and Unicode characters also need or can be correspondingly escaped.

If you directly insert an unprocessed dynamic content (such as a document description containing double quotes or newline characters) into a JSON string, it may break the JSON syntax structure and cause parsing errors.

addslashesLimitations in the JSON scenario

Return to the original question:addslashesCan the filter provide help? The answer is:It can provide some help, but it cannot solve the problem completely.

addslashesThe filter can indeed handle double quotes in dynamic content (") and backslash (\) and escape them as\"and\\This exactly meets the JSON escaping requirements for these two characters. It is very useful in this aspect.

However,addslashesThe limitation is that it only focuses on these specific characters.won'tRegarding the newline character (\nParentheses and newline\r), tab characters (\t)or other control characters need to be escaped. If your dynamic content contains these characters, simply usingaddslasheswill still result in an invalid JSON string.

For example, a document description这是一段包含\n换行符和"引号"的文本。afteraddslashesAfter processing, it may become这是一段包含\n换行符和\"引号\"的文本。. Although the double quotes are escaped, the newline character\nis not, which is a syntax error in JSON.

A more reliable solution

In an ideal case, a mature CMS template engine should provide a dedicated JSON encoding filter (such as the standard library in Go language)encoding/jsonA package that can safely serialize any Go data type into a JSON-compliant string.This filter will be responsible for all necessary character escaping, including new lines, tabs, Unicode characters, and so on.

If the AnQiCMS template does not provide such a comprehensive one directlyjson_encodeOr similar filters (not directly found in the provided document), then it becomes very difficult and cumbersome to directly build complex JSON strings in the template and ensure their complete safety. In this case, there are several suggestions to consider:

  1. Backend preprocessing:The most recommended approach is to pre-encode the dynamic content that needs to be output as JSON in the Go language backend code of AnQiCMS. For example, encode a struct or map through Go'sjson.MarshalConvert function to JSON string, then pass this encoded JSON string as a variable to the template.This, the template only needs to output this variable directly, without any additional filters.
    
    // Go 后端代码示例
    type Data struct {
        Title       string `json:"title"`
        Description string `json:"description"`
    }
    
    // 假设 archiveData 是从数据库获取的动态内容
    dataToEncode := Data{
        Title:       archiveData.Title,
        Description: archiveData.Description,
    }
    
    jsonString, err := json.Marshal(dataToEncode)
    if err != nil {
        // 处理错误
    }
    // 将 jsonString 传递给模板渲染
    
    In the template: “`twig