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

3

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

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

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

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

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
source

2 answers

2

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
    1

    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.

    link

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