HTML模板中的未定义函数

时间:2019-07-19 15:48:32

标签: templates go

我无法使用以下语法/步骤将自定义函数传递给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。我想念什么?

P.S。请不要提供其他解析模板的方式,例如template.New...等。我希望使用此语法。

1 个答案:

答案 0 :(得分:1)

使用此功能:

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)

Run it on the Go Playground