PrecisionPete
PrecisionPete

Reputation: 3401

How to render HTML without escaping in Go templates?

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>

Upvotes: 3

Views: 6924

Answers (1)

Cookie04
Cookie04

Reputation: 215

You can use html/template's HTML type.

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

Upvotes: 9

Related Questions