Inserting HTML into Go Templates
When working with Go templates, it's important to consider how you insert HTML content to avoid unexpected behavior. For instance, inserting a string containing HTML code can lead to unwanted character escaping, resulting in incorrect output.
To handle HTML insertion correctly in Go templates, follow these guidelines:
Pass HTML as template.HTML:
Instead of passing a string directly, wrap your HTML content in a template.HTML type. This tells the template engine to treat the content as raw HTML, preventing it from escaping characters.
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) //OUTPUT: <p>Paragraph</p>&lt;p&gt;Paragraph&lt;/p&gt;</code>
Avoid Passing Strings:
Passing HTML content as a string can lead to unwanted escaping. For example:
<code class="go">tpl := template.Must(template.New("main").Parse(`{{define "T"}}{{.Html}}<p>{{.String}}</p>{{end}}`)) tplVars := map[string]interface{} { "Html": "<p>Paragraph</p>", "String": "<p>Paragraph</p>", } tpl.ExecuteTemplate(os.Stdout, "T", tplVars) //OUTPUT: <p>Paragraph</p>&lt;p&gt;Paragraph&lt;/p&gt;</code>
JSON Data:
If you're inserting JSON data into your template, you can use a library like encoding/json to encode it as a string. Then, you can pass the encoded string to the template and decode it within the template using the json template function.
The above is the detailed content of How Can I Insert HTML into Go Templates Without Escaping?. For more information, please follow other related articles on the PHP Chinese website!