In AnQiCMS templates, handling dynamic content and embedding it safely into JSON strings is a common requirement, especially when backend data needs to be passed to frontend JavaScript. When encountering such a scenario, many users would naturally think of usingaddslashesThis filter is used to process special characters. Then,addslashesCan the filter help with this? Let's delve deeper into it.

AnQiCMS template and dynamic content

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

addslashesThe role of the filter

According to AnQiCMS documentation,addslashesThe filter is mainly used to add a backslash before the specified predefined characters in a string. These predefined characters include: single quotes ('), double quote ()") and the backslash (\)\)。Its main purpose is 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).

Give an example, if you have a stringThis is a "test" with a 'single quote' and a backslash \.afteraddslashesafter processing, it may becomeThis is a \"test\" with a \'single quote\' and a backslash \\.. Usually, this filter will be used with|safeto ensure that it is not doubly escaped when output to HTML.

When content encounters a JSON string

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, but used with numbers and strings and arrays and objects. In JSON, strings must be enclosed in double quotes, and special characters within strings must be escaped, for example:

  • Double quotes"必须转义为\"
  • 反斜杠\必须转义为\\
  • 换行符\n必须转义为\\n
  • 回车符\r必须转义为\\r
  • 制表符\t必须转义为\\t
  • 其他一些控制字符和Unicode字符也需要或可以进行相应的转义。

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

addslashesLimitations in JSON scenarios

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

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

However,addslashesLimitations lie in its focus on only these specific characters. Itwill notfor line breaks (\n)、carriage return(\rtabs (\t)or other control characters should be escaped. If your dynamic content contains these characters, just using addslasheswill still result in an invalid JSON string.

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

A more robust solution

Under ideal circumstances, a mature CMS template engine should provide a dedicated JSON encoding filter (for example, the standard library in Go language)encoding/json包),能够将任何Go类型的数据安全地序列化为符合JSON规范的字符串。This filter will be responsible for all necessary character escaping, including new lines, tabs, Unicode characters, etc.

If the AnQiCMS template does not provide such a comprehensive one directlyjson_encodeIf an auto filter or similar is not found (not directly discovered from the provided documents), it will become very difficult and cumbersome to directly construct complex JSON strings in the template and ensure their complete safety. In this case, the following suggestions are available:

  1. Backend preprocessing:The 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.MarshalFunction is converted to a JSON string, then this encoded JSON string is passed as a variable to the template.Thus, the template only needs to directly output this variable 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