Skip to content

Instantly share code, notes, and snippets.

@vadviktor
Created July 6, 2018 14:04
Show Gist options
  • Select an option

  • Save vadviktor/49ee28130a86a8ec1c12dc594c2c2a73 to your computer and use it in GitHub Desktop.

Select an option

Save vadviktor/49ee28130a86a8ec1c12dc594c2c2a73 to your computer and use it in GitHub Desktop.
Go: Nested maps access in a template
package main
import (
"log"
"os"
"text/template"
)
func main() {
var urls = map[string]map[string]string{}
urls["pic1"] = make(map[string]string)
urls["pic1"]["small"] = "pic1-small-url"
urls["pic1"]["large"] = "pic1-large-url"
urls["pic2"] = make(map[string]string)
urls["pic2"]["small"] = "pic2-small-url"
urls["pic2"]["large"] = "pic2-large-url"
urls["pic3"] = make(map[string]string)
urls["pic3"]["small"] = "pic3-small-url"
urls["pic3"]["large"] = "pic3-large-url"
tpl := template.Must(template.New("content").Parse(`
{{.small}} - {{.large}}
`))
for _, r := range urls {
err := tpl.Execute(os.Stdout, r)
if err != nil {
log.Printf("%s\n", err.Error())
}
}
/* output:
pic1-small-url - pic1-large-url
pic2-small-url - pic2-large-url
pic3-small-url - pic3-large-url
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment