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

2

1 Answer

You can use a raw string constant.

tpl := template.Must(template.New("").Parse("{{`{{Hello World}}`}}"))
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like