首页 > 解决方案 > 在模板中转义大括号

问题描述

如何在 golangs 模板系统中转义大括号?
假设我要打印{{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

解决方案


您可以使用原始字符串常量。

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

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


推荐阅读