dongmo9996 2018-07-13 13:14
浏览 70
已采纳

转义模板中的大括号

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

  • 写回答

1条回答 默认 最新

  • doushui5587 2018-07-13 13:22
    关注

    You can use a raw string constant.

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

    https://play.golang.org/p/FmPo6uMUBp8

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?