Eun
Eun

Reputation: 4178

escape curly brackets in templates

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")
}

go playground

Upvotes: 18

Views: 18101

Answers (1)

Massimo Zerbini
Massimo Zerbini

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

Related Questions