Home  >  Article  >  Backend Development  >  How Can I Insert HTML into Go Templates Without Escaping?

How Can I Insert HTML into Go Templates Without Escaping?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 04:38:28888browse

How Can I Insert HTML into Go Templates Without Escaping?

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>&amp;lt;p&amp;gt;Paragraph&amp;lt;/p&amp;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>&amp;lt;p&amp;gt;Paragraph&amp;lt;/p&amp;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!

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