在 Go 模板中,有时将正确的数据传递给正确的模板的方式让我感觉很尴尬。调用带有管道参数的模板看起来就像调用只有一个参数的函数。
假设我有一个关于 Gophers 的 Gophers 网站。它有一个主页主模板和一个打印 Gophers 列表的实用程序模板。
http://play.golang.org/p/Jivy_WPh16
输出 :
*The great GopherBook* (logged in as Dewey)
[Most popular]
>> Huey
>> Dewey
>> Louie
[Most active]
>> Huey
>> Louie
[Most recent]
>> Louie
现在我想在子模板中添加一些上下文:在列表中以不同的方式格式化名称“Dewey”,因为它是当前登录用户的名称。但我不能直接传递名称,因为[只有一个](http://golang.org/pkg/text/template/#hdr- Actions)可能的“点”参数管道!我能做些什么?
您可以在模板中注册一个“dict”函数,您可以使用该函数将多个值传递给模板调用。调用本身将如下所示:
{{template "userlist" dict "Users" .MostPopular "Current" .CurrentUser}}
小“dict”助手的代码,包括将其注册为模板 func 在这里:
var tmpl = template.Must(template.New("").Funcs(template.FuncMap{
"dict": func(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, errors.New("invalid dict call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i+=2 {
key, ok := values[i].(string)
if !ok {
return nil, errors.New("dict keys must be strings")
}
dict[key] = values[i+1]
}
return dict, nil
},
}).ParseGlob("templates/*.html")