英文:
How to print JSON on golang template?
问题
我需要在客户端中使用一个对象,所以我使用json.marshal将其转换为JSON,并将其打印到模板中。该对象被打印为转义的JSON字符串。
我期望它是var arr=["o1","o2"]
,但实际上是var arr="[\\"o1\\",\\"o2\\"]"
。
我知道我可以在客户端使用JSON.parse,但这是唯一的方法吗?
以下是我在模板中打印它的方式:
{{ marshal .Arr }}
这是我的marshal函数:
"marshal": func(v interface {}) string {
a, _ := json.Marshal(v)
return string(a)
},
英文:
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.
I'm expecting it to be var arr=["o1","o2"]
but it is var arr="[\"o1\",\"o2\"]"
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 }}
Here is my marshal function:
"marshal": func(v interface {}) string {
a, _ := json.Marshal(v)
return string(a)
},
答案1
得分: 34
在JS上下文中,普通字符串总是会被转义。在打印之前,我应该将其转换为template.JS
类型。
参考链接:
http://golang.org/pkg/html/template/#JS
这是新的编组函数:
"marshal": func(v interface{}) template.JS {
a, _ := json.Marshal(v)
return template.JS(a)
},
英文:
In JS context normal strings always gets escaped. I should have converted to template.JS
type before printing.
Ref:
http://golang.org/pkg/html/template/#JS
This is new marshal function:
"marshal": func(v interface {}) template.JS {
a, _ := json.Marshal(v)
return template.JS(a)
},
答案2
得分: 0
如果你的模板中有<script>
元素,你可以直接传递一个map[string]interface{}
,或者一般情况下,任何encoding/json
包能够转换为JSON的内容,比如切片、结构体等。
Go的html/template
模板根据上下文进行渲染:
该包理解HTML、CSS、JavaScript和URI。它为每个简单操作管道添加了清理函数[...]。
在解析时,每个
{{.}}
都会被覆盖,根据需要添加转义函数。
因此,使用html/template
不需要事先转换为JSON。引擎会根据需要自动完成。
package main
import (
"html/template"
"os"
)
const s = `<script>var arr={{.}}</script>`
func main() {
t, _ := template.New("").Parse(s)
t.Execute(os.Stdout, []string{"o1", "o2"})
// 字符串切片会被encoding/json包转换为JSON数组
}
输出结果为:
<script>var arr=["o1","o2"]</script>
Playground: https://go.dev/play/p/7TMbEwbKNYi
英文:
If your template has <script>
elements, you can just pass a map[string]interface{}
— or in general, anything that the encoding/json
package would be able to marshal to JSON, like slices, structs, etc.
Go html/template
templates render based on contexts:
> This package understands HTML, CSS, JavaScript, and URIs. It adds sanitizing functions to each simple action pipeline [...]
>
> At parse time each {{.}}
is overwritten to add escaping functions as necessary.
Therefore it is not necessary with html/template
to marshal to JSON beforehand. The engine will do it as appropriate.
package main
import (
"html/template"
"os"
)
const s = `<script>var arr={{.}}</script>`
func main() {
t, _ := template.New("").Parse(s)
t.Execute(os.Stdout, []string{"o1", "o2"})
// string slice is marshalled by encoding/json package as JSON array
}
Prints:
<script>var arr=["o1","o2"]</script>
Playground: https://go.dev/play/p/7TMbEwbKNYi
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论