Home >Backend Development >Golang >How to Insert HTML into Go Templates Without Escaping?
When defining a Go template with HTML elements, it's important to avoid unintentionally escaping characters that should be rendered as part of the HTML. This issue arises when using a string to represent the HTML content within the template.
To prevent escaping, the correct approach is to pass the HTML content as an instance of template.HTML. This type is responsible for handling the rendering of HTML within Go templates, ensuring that it is displayed without escaping.
An example demonstrating this technique:
<code class="go">package main import ( "fmt" "html/template" "os" ) func main() { 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>
In this example, the HTML content is passed as a template.HTML value, which prevents escaping from occurring. The output is displayed as intended, without any escaped HTML characters.
The above is the detailed content of How to Insert HTML into Go Templates Without Escaping?. For more information, please follow other related articles on the PHP Chinese website!