1

I receive from my frontend a json with a string containing 1 or more HTML elements for example:

"textTop" : "<b>bold</b><div><i>italic</i>..."

I want to use this string to create Html elements inside a div, but I'm not really sure if I can do this with golang templates.

type FooBar struct {
    TextTop    string
}

So I'm currently storing the TextTop in a string, and then displaying it in html with:

        <div>
            {{.TextTop}}
        </div>

But of course this produces the following result in the browser. just a div containing the string, I'm passing.: enter image description here

So should I use a different type for TextTop inside Foobar struct instead of type string, which one? or can I use a golang function that reads all html elements from a string and renders them in the html as part of the DOM and not just a string?

CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186
  • Possible duplicate of [Inserting HTML to golang template](https://stackoverflow.com/questions/41931082/inserting-html-to-golang-template) – leaf bebop Jan 27 '18 at 15:35

1 Answers1

3

To prevent escaping, declare the field as type template.HTML:

type FooBar struct {
    TextTop    template.HTML
}

See the linked documentation for information about the security risks of using template.HTML.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242