"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Avoid Unintended Escaping of HTML and JSON in Go Templates?

How to Avoid Unintended Escaping of HTML and JSON in Go Templates?

Published on 2024-11-09
Browse:114

How to Avoid Unintended Escaping of HTML and JSON in Go Templates?

Escaping HTML and JSON in Go Templates

In Go templates, it's essential to handle HTML and JSON properly to prevent unintended escaping. Consider the following template:

 {{ .SomeOtherHTML }} 

If you expect the output to be simply , you may encounter the issue where special characters like

 <the_other_html/< 

Solution for HTML Escaping

To prevent this, you should pass the HTML code as a template.HTML type instead of a string. template.HTML is a special type that instructs Go not to escape its content. For example:

tpl := template.Must(template.New("main").Parse(`{{define "T"}}{{.Html}}{{.String}}{{end}}`))
tplVars := map[string]interface{} {
    "Html": template.HTML("

Paragraph

"), "String": "

Paragraph

", } tpl.ExecuteTemplate(os.Stdout, "T", tplVars)

Solution for JSON Escaping

If you also need to render JSON, you should use the json.Marshal function to convert it into a byte array. This prevents Go from escaping the JSON content. For example:

jsonBytes, _ := json.Marshal(data)
outputString := string(jsonBytes)

By following these best practices, you can ensure proper escaping of HTML and JSON in your Go templates, resulting in the desired output without unintended modifications.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3