使用html/template我正在尝试在模板中使用自己的功能之一。不幸的是,我无法使用go模板的功能映射功能。我得到的只是以下错误:
html/template
% go run test.go panic: template: tmpl.html:5: function "humanSize" not defined [...]
简化的测试用例如下所示(test.go):
test.go
package main import ( "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):
tmpl.html
<html><body> {{range .}} <div> <span>{{.Name}}</span> <span>{{humanSize .Size}}</span> </div> {{end}} </body></html>
这是1.1.1。
IIRC,必须.Funcs在解析模板之前定义模板功能图。下面的代码似乎有效。
.Funcs
package main import ( "html/template" "io/ioutil" "net/http" "strconv" ) var funcMap = template.FuncMap{ "humanSize": humanSize, } const tmpl = ` <html><body> {{range .}} <div> <span>{{.Name}}</span> <span>{{humanSize .Size}}</span> </div> {{end}} </body></html>` var tmplGet = template.Must(template.New("").Funcs(funcMap).Parse(tmpl)) func humanSize(s int64) string { return strconv.FormatInt(s/int64(1000), 10) + " KB" } func getPageHandler(w http.ResponseWriter, r *http.Request) { files, err := ioutil.ReadDir(".") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if err := tmplGet.Execute(w, files); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func main() { http.HandleFunc("/", getPageHandler) http.ListenAndServe(":8080", nil) }