How to print JSON on golang template?

huangapple go评论86阅读模式
英文:

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 &lt;script&gt; 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 (
	&quot;html/template&quot;
	&quot;os&quot;
)

const s = `&lt;script&gt;var arr={{.}}&lt;/script&gt;`

func main() {
	t, _ := template.New(&quot;&quot;).Parse(s)
	t.Execute(os.Stdout, []string{&quot;o1&quot;, &quot;o2&quot;}) 
    // string slice is marshalled by encoding/json package as JSON array

}

Prints:

&lt;script&gt;var arr=[&quot;o1&quot;,&quot;o2&quot;]&lt;/script&gt;

Playground: https://go.dev/play/p/7TMbEwbKNYi

huangapple
  • 本文由 发表于 2014年1月31日 22:51:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/21482948.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定