Skip to content

Instantly share code, notes, and snippets.

@roshanraj
Created October 3, 2018 04:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roshanraj/2ab93aa652f51b509705c0cc5d834499 to your computer and use it in GitHub Desktop.
Save roshanraj/2ab93aa652f51b509705c0cc5d834499 to your computer and use it in GitHub Desktop.
using map in templates
package main
import (
"encoding/json"
"fmt"
"text/template"
"os"
)
type StatusType struct {
Id string `json:"message_id,omitempty"`
Status map[string]interface{} `json:"status,omitempty"`
}
func main() {
var s StatusType
s.Id = "12345"
m := make(map[string]interface{})
s.Status = m
// Now this works
// s.Status["x-value"] = "foo1234"
// s.Status["y-value"] = "bar4321"
// And this works
sites := []string{"a", "b", "c", "d"}
s.Status["site-value"] = sites
s.Status["hello"] = "game of throne"
var data []byte
data, _ = json.MarshalIndent(s, "", " ")
fmt.Println(string(data))
tmpl := `
this is a template to test map interface {{index .Status "hello"}}
`
t := template.New("testfunc")
tt, err := t.Parse(tmpl)
if err != nil {
panic(err)
}
if err = tt.Execute(os.Stdout, &s); err != nil {
fmt.Println(err)
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment