Skip to content

Instantly share code, notes, and snippets.

@garyburd
Created November 15, 2011 21:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save garyburd/1368458 to your computer and use it in GitHub Desktop.
Save garyburd/1368458 to your computer and use it in GitHub Desktop.
Execute child template with map constructed from values in parent template.
package main
import (
"errors"
"log"
"os"
"text/template"
)
func mapfn(kvs ...interface{}) (map[string]interface{}, error) {
if len(kvs)%2 != 0 {
return nil, errors.New("map requires even number of arguments.")
}
m := make(map[string]interface{})
for i := 0; i < len(kvs); i += 2 {
s, ok := kvs[i].(string)
if !ok {
return nil, errors.New("even args to map must be strings.")
}
m[s] = kvs[i+1]
}
return m, nil
}
func main() {
var s = template.New("")
s.Funcs(template.FuncMap{"map": mapfn})
_, err := s.Parse(`
{{define "parent"}}{{template "child" map "a" 1 "b" 2}}{{end}}
{{define "child"}}a={{$.a}}, b={{$.b}}{{end}}
`)
if err != nil {
log.Fatal(err)
}
err = s.ExecuteTemplate(os.Stdout, "parent", nil)
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment