如何在golang模板上打印JSON?

Cha*_*aju 12 go go-templates

我需要客户端的对象,所以我使用json.marshal将其转换为JSON并将其打印到模板中.该对象将作为转义的JSON字符串打印.

我期待它,var arr=["o1","o2"]但确实如此var arr="[\"o1\",\"o2\"]"

我知道我可以在客户端使用JSON.parse,但这是唯一的方法吗?

这是我在模板中打印的方式:

{{ marshal .Arr }}

这是我的元帅功能:

"marshal": func(v interface {}) string {
  a, _ := json.Marshal(v)
  return string(a)
},
Run Code Online (Sandbox Code Playgroud)

Cha*_*aju 22

在JS上下文中,常规字符串总是被转义.我应该template.JS在打印前转换为类型.

参考:http: //golang.org/pkg/html/template/#JS

这是新的元帅功能:

"marshal": func(v interface {}) template.JS {
  a, _ := json.Marshal(v)
  return template.JS(a)
},
Run Code Online (Sandbox Code Playgroud)

  • 更容易理解一点:`encodedValue := json.Marshal(complexValue); ReplaceableValue := template.JS(encodedValue)` (2认同)