使用html/template我試圖在模板中使用我自己的功能之一。不幸的是,我無法使用 go 模板的函數(shù)映射功能。我得到的只是以下錯誤:% go run test.gopanic: template: tmpl.html:5: function "humanSize" not defined[...]簡化的測試用例如下 ( test.go):package mainimport ( "html/template" "io/ioutil" "net/http" "strconv")var funcMap = template.FuncMap{ "humanSize": humanSize,}var tmplGet = template.Must(template.ParseFiles("tmpl.html")).Funcs(funcMap)func humanSize(s int64) string { return strconv.FormatInt(s/int64(1000), 10) + " KB"}func getPageHandler(w http.ResponseWriter, r *http.Request) { files, _ := ioutil.ReadDir(".") if err := tmplGet.Execute(w, files); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) }}func main() { http.HandleFunc("/", getPageHandler) http.ListenAndServe(":8080", nil)}我有以下簡單模板 ( tmpl.html):<html><body> {{range .}} <div> <span>{{.Name}}</span> <span>{{humanSize .Size}}</span> </div> {{end}}</body></html>這是 1.1.1。
模板和自定義功能;恐慌:功能未定義
慕無忌1623718
2021-06-08 13:19:46