Is it possible to modify the JSON options in html / template?


html/template has a very convenient feature. If I have a template like this:

<script>var x = '{{ .Data }}';</script>

The variable Data can be of any type, and html/template converts it to JSON. For example:

<script>var x = '{"nombre":"José","edad":32}';</script>

My question is: Is it possible to use different options for the JSON format? I would like, for example, to use json.MarshalIndent() to make the template output easier to read.

asked by Flimzy 11.09.2016 в 20:52

2 answers


You can use Custom Template Functions ( custom template functions ) to give it the desired format.

  • We define the function marshalindent , which returns a template.JSStr (with valid escapes within a string of

  • answered by 13.09.2016 в 01:29

    I do not know the go language, I had never seen it, but I can give an answer that I could develop by researching on the internet.

    Suppose this example, we have the following structure.

    type keyvalue struct {Nombre, Edad string}

    With the following values.

    x := []keyvalue{{"José", "32"}}

    In the following line you can see how I use MarshalIndent , put \t to tabulate.

    json, _ := json.MarshalIndent(x, "", "\t")

    The result is indented as follows.

            "Nombre": "José",
            "Edad": "32"

    Final code.


    package main
    import (
    func main() {
        type keyvalue struct {
            Nombre, Edad string
        x := []keyvalue{{"José", "32"}}
        tr, err := template.New("tr").Parse("{{.}}")
        if err != nil {
        json, _ := json.MarshalIndent(x, "", "\t")
        err = tr.ExecuteTemplate(os.Stdout, "tr", template.HTML(json))
    answered by 12.09.2016 в 12:27