我正在尝试向模板中添加一个用于“人性化”(https://gowalker.org/github.com/dustin/go-humanize)输出的函数,但似乎我做错了,因为出现了此错误:
panic :模板:dashboard.tmpl:192:函数“humanizeTime”未定义
func renderTemplate(w http.ResponseWriter, name string, data map[string]interface{}) error {
//functions for templates
templateFuncs := template.FuncMap{
"humanizeTime": func(t time.Time) string {
return humanize.Time(t)
},
}
tmpl := Templates[name+".tmpl"].Funcs(templateFuncs)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err := tmpl.ExecuteTemplate(w, name, data)
if err != nil {
log.Printf("Error rendering template: %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return errors.New("Error trying to render template")
}
return nil
}
添加:
我正在定义并加载init()我的模板Map:
var Templates map[string]*template.Template
if Templates == nil {
Templates = make(map[string]*template.Template)
}
layouts, err := filepath.Glob("templates/*.tmpl")
if err != nil {
panic(err)
}
for _, layout := range layouts {
Templates[filepath.Base(layout)] = template.Must(template.ParseFiles(layouts...))
}
我只是将定义更改为:
for _, layout := range layouts {
Templates[filepath.Base(layout)] = template.Must(template.ParseFiles(layouts...)).Funcs(templateFuncs)
}
但是还不行,我遇到了同样的错误:未定义。
请有人帮我吗?谢谢。
最佳答案
将功能附加到模板后,需要在模板上调用Parse()
。我不知道您的模板映射是如何定义的,但是假设它是模板文本的映射,则调用应如下所示:
tmpl := template.New(templateName).Funcs(template.FuncMap{
....
}).Parse(Templates[name+".tmpl"])
如果
Templates
包含已解析的模板,则在解析它们时需要附加该函数。关于templates - Golang : Help registering a function into templates,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30685872/