我試圖在我的模板中添加一個函數(shù)來“人性化”(https://gowalker.org/github.com/dustin/go-humanize)輸出,但似乎我做錯了,因為我得到了這個錯誤:恐慌:模板:dashboard.tmpl:192:未定義函數(shù)“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() 上定義和加載我的模板映射:var Templates map[string]*template.Templateif 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)}但還沒有工作,我得到了同樣的錯誤:未定義。請問有人可以幫我嗎?謝謝。
- 2 回答
- 0 關(guān)注
- 355 瀏覽
添加回答
舉報
0/150
提交
取消