I'm trying to add to my templates a function to "humanize"(https://gowalker.org/github.com/dustin/go-humanize) the output, but seems something I'm doing wrong because I'm getting this error:
panic: template: dashboard.tmpl:192: function "humanizeTime" not defined
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
}
Added: I am defining and loading on init() my templates 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...))
}
I just change my definition to:
for _, layout := range layouts {
Templates[filepath.Base(layout)] = template.Must(template.ParseFiles(layouts...)).Funcs(templateFuncs)
}
But doesn't work yet, I got the same error: not defined.
Please could somebody give me a hand with that? Thanks.