How to print JSON on golang template?
Asked Answered
A

2

21

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)
},
Achaea answered 31/1, 2014 at 14:51 Comment(0)
A
35

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)
},
Achaea answered 31/1, 2014 at 15:5 Comment(1)
A little more understandable: encodedValue := json.Marshal(complexValue); replaceableValue := template.JS(encodedValue)Blubberhead
E
0

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

Edwardoedwards answered 20/11, 2022 at 20:16 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.