转义模板中的大括号

Eun*_*Eun 3 go

如何在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")
}
Run Code Online (Sandbox Code Playgroud)

去操场

Mas*_*ini 5

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

tpl := template.Must(template.New("").Parse("{{`{{Hello World}}`}}"))
Run Code Online (Sandbox Code Playgroud)

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

  • 这实际上只适用于单行字符串或以编程方式生成的字符串。大多数时候,如果您处理模板文字,则需要使用 Go 的“\”字符串语法,该语法不允许在字符串本身中使用“\”标记。:/ (3认同)