0

How do I render "safe" HTML in a Go HTML template? i.e. without having the template engine escape it? e.g. If I am pulling HTML fragments from elsewhere - like a database?

Specifically... I have some lengthy Terms & Conditions that are stored in a string. They need to be used in various places and a Template of their own is not the ideal way to include them.

It's really not convenient to have to keep everything HTML in a template... Other languages have a way of designating the injected content as safe to render.

How do I do this in Go? I know it's in there somewhere. I just can't find it in the docs.

In the handler...

    hello := "<p><i>Hello</i>"
    data["Hello"] = hello
    Render it and pass data...

In the template...

    <h1>Show Stuff</h1>      
    {{.Hello}}

In the browser...

Show Stuff
<p><i>Hello</i>
PrecisionPete
  • 3,139
  • 5
  • 33
  • 52
  • 1
    Does the following help? https://stackoverflow.com/questions/43458824/parsing-unescaped-html-to-html-template-in-go/43459037#43459037 (https://golang.org/pkg/html/template/#HTML) Note the answer in the link suggests a custom template function, but you don't have to take that approach, you can simply convert `hello` to the safe-html type and use it as such. i.e. if `data` is of type `map[string]interface{}` or `map[string]template.HTML` then you can do `data["Hello"] = template.HTML(hello)` and that's it. – mkopriva May 02 '21 at 16:29
  • go doc html/template.HTML – Volker May 02 '21 at 16:55
  • I knew it had to be that easy... Thanks – PrecisionPete May 02 '21 at 21:09

1 Answers1

3

You can use html/template's HTTP type.

Just convert your string like this: template.HTML("your html here").

Cookie04
  • 155
  • 2
  • 11