Created
November 15, 2011 21:42
-
-
Save garyburd/1368458 to your computer and use it in GitHub Desktop.
Execute child template with map constructed from values in parent template.
This file contains 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 ( | |
"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