Created
October 3, 2018 04:44
-
-
Save roshanraj/2ab93aa652f51b509705c0cc5d834499 to your computer and use it in GitHub Desktop.
using map in templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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