Home > Backend Development > Golang > How to Insert HTML into Go Templates Without Escaping?

How to Insert HTML into Go Templates Without Escaping?

DDD
Release: 2024-10-29 10:02:30
Original
382 people have browsed it

How to Insert HTML into Go Templates Without Escaping?

Inserting 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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template