1

I am working on a template that is powered by Go's html/template package, and I have a specific string value that is passed into the template that needs to be unescaped. The one constraint is that I cannot render the entire template through text/template, it must be rendered through html/template.

I have a simplified example of the problem here:

package main

import (
    "log"
    "os"
    "html/template"
)

func main() {
    templateStr := `<input type="text" data-thing="{{.dataThing}}"/>`


    tmpl, err := template.New("").Parse(templateStr)
    if err != nil {
        log.Fatal(err)
        return
    }
    
    tmpl.Execute(os.Stdout, map[string]string{"dataThing":"this->shouldNotEscape"})
}

The current output of the template is: <input type="text" data-thing="this-&gt;shouldNotEscape"/>.

But the desired output of the template is: <input type="text" data-thing="this->shouldNotEscape"/>.

I have a runnable Go Playground here.

Johnnie
  • 197
  • 1
  • 9
  • https://golang.org/pkg/html/template/#hdr-Typed_Strings – Adrian Aug 19 '20 at 18:21
  • @Adrian I've attempted to wrap the string with `template.HTML` but it still fails. Example is here: https://play.golang.org/p/EyIjCk-f_Hd – Johnnie Aug 19 '20 at 18:24
  • "It still fails" meaning what? How did you use it when you tried it? Your code does not show use of `template.HTML`, which is the solution to the problem you've described. – Adrian Aug 19 '20 at 18:25
  • @Adrian see my edited prior comment. I've wrapped the wanted unescaped string with the `template.HTML` call, but on render, the string is still being escaped inside the attribute value. – Johnnie Aug 19 '20 at 18:26

0 Answers0