如何在golang模板上打印JSON? [英] How to print JSON on golang template?
本文介绍了如何在golang模板上打印JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在客户端需要一个对象,因此我使用json.marshal将其转换为JSON并将其打印到模板中.该对象将作为转义的JSON字符串打印.
I need a object in client side, so I converted it to JSON using json.marshal and printed it into template. The object is getting printed as escaped JSON string.
我希望它是 var arr = ["o1","o2"]
,但它是 var arr ="[\" o1 \,\" o2 \]"
我知道我可以在客户端进行JSON.parse,但这是唯一的方法吗?
I know I can JSON.parse in client side, but is that the only way?
这是我在模板中打印的方式:
Here is how I'm printing it in template:
{{marshal .Arr}}
这是我的元帅职能:
"marshal": func(v interface {}) string {
a, _ := json.Marshal(v)
return string(a)
},
推荐答案
在JS上下文中,常规字符串始终会被转义.在打印之前,我应该已经转换为 template.JS
类型.
In JS context normal strings always gets escaped. I should have converted to template.JS
type before printing.
参考: http://golang.org/pkg/html/template/#JS
这是新的元帅功能:
"marshal": func(v interface {}) template.JS {
a, _ := json.Marshal(v)
return template.JS(a)
},
这篇关于如何在golang模板上打印JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文