代码之家  ›  专栏  ›  技术社区  ›  Eun

在模板中转义花括号

go
  •  2
  • Eun  · 技术社区  · 8 年前

    如何避开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 playground

    1 回复  |  直到 8 年前
        1
  •  4
  •   Massimo Zerbini    8 年前

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

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