我無法使用以下語法/步驟將自定義函數傳遞給 HTML 模板:t, err := template.ParseFiles("name.tpl")if err != nil { return}err = t.Funcs(template.FuncMap{"add": add}).Execute(w, nil)if err != nil { return}.........func add(a int8, b int8) int8 { return a + b}所需的功能是add,編譯期間沒有錯誤,但在嘗試渲染 HTML 模板時出現錯誤function "add" not defined。我缺少什么?PS請不要提供其他解析模板的方法,諸如此類template.New...。我希望使用這個語法。
1 回答

慕絲7291255
TA貢獻1859條經驗 獲得超6個贊
使用這個函數:
func parseFiles(funcs template.FuncMap, filenames ...string) (*template.Template, error) {
return template.New(filepath.Base(filenames[0])).Funcs(funcs).ParseFiles(filenames...)
}
像這樣稱呼它:
t, err := parseFiles(template.FuncMap{"add": add}, "name.tpl")
if err != nil {
return
}
err = t.Execute(w, nil)
在 Go Playground 上運行它。
- 1 回答
- 0 關注
- 140 瀏覽
添加回答
舉報
0/150
提交
取消