20

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)
},

2 Answers 2

34

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)
},
1
  • 2
    A little more understandable: encodedValue := json.Marshal(complexValue); replaceableValue := template.JS(encodedValue) Aug 6, 2016 at 15:48
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.