Original post

I am trying to understand how html templates works with json. Found an example:

https://play.golang.org/p/EOVypH5ONHn

…and tried to add {{range.}} to it, but it gets errors:

https://play.golang.org/p/vrwx01z0_0o

package main

import (
        "encoding/json"
        "html/template"
        "os"
)

func main() {
        t := template.Must(template.New("").Parse(templ))

        m := map[string]interface{}{}
        if err := json.Unmarshal([]byte(jsondata), &m); err != nil {
                panic(err)
        }

        if err := t.Execute(os.Stdout, m); err != nil {
                panic(err)
        }
}

const templ = `<html><body>
        {{range.}}      
              {{.something}}
              {{.somethingElse}}
        {{end}}
</body></html>`

const jsondata = `{"something":"valueofa", "somethingElse": 1234}`

What am I doing wrong? Why does it work without {{range.}}?

If you want to loop over the items in the JSON object, you could do something like this:

const templ = `<html><body>
{{ range $key, $value := . }}
   <li>{{ $key }}: {{ $value }}</li>
{{ end }}
</body></html>`

Output:

<html><body>
   <li>something: valueofa</li>
   <li>somethingElse: 1234</li>
</body></html>

See https://play.golang.org/p/lpRqZPmPsy1