Reputation: 4178
How do I escape curly brackets in golangs template system?
Assume I want to print {{Hello World}}
:
var buf bytes.Buffer
// tpl := template.Must(template.New("").Parse(`{{ print "{{Hello World}}"}}`)) // this is working
tpl := template.Must(template.New("").Parse(`\{\{Hello World\}\}`)) // this is not
if err := tpl.Execute(&buf, nil); err != nil {
panic(err)
}
if buf.String() != "{{Hello World}}" {
panic("Unexpected")
}
Upvotes: 18
Views: 18101
Reputation: 3191
You can use a raw string constant.
tpl := template.Must(template.New("").Parse("{{`{{Hello World}}`}}"))
https://play.golang.org/p/FmPo6uMUBp8
Upvotes: 25