Home >Backend Development >Golang >How to Avoid Unintended Escaping of HTML and JSON in Go Templates?

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

DDD
DDDOriginal
2024-11-03 04:17:02446browse

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:

<some_html> {{ .SomeOtherHTML }} </some_html>

If you expect the output to be simply , you may encounter the issue where special characters like < and & are escaped, resulting in an unexpected output:

<some_html> <the_other_html/< </some_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:

<code class="go">tpl := template.Must(template.New("main").Parse(`{{define "T"}}{{.Html}}{{.String}}{{end}}`))
tplVars := map[string]interface{} {
    "Html": template.HTML("<p>Paragraph</p>"),
    "String": "<p>Paragraph</p>",
}
tpl.ExecuteTemplate(os.Stdout, "T", tplVars)</code>

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:

<code class="go">jsonBytes, _ := json.Marshal(data)
outputString := string(jsonBytes)</code>

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.

The above is the detailed content of How to Avoid Unintended Escaping of HTML and JSON in Go Templates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn