当我尝试访问传递给模板的函数时遇到错误:
Error: template: struct.tpl:3: function "makeGoName" not defined
任何人都可以让我知道我做错了什么吗?
模板文件(struct.tpl):
type {{.data.tableName}} struct {
{{range $key, $value := .data.tableData}}
{{makeGoName $value.colName}} {{$value.colType}} `db:"{{makeDBName $value.dbColName}},json:"{{$value.dbColName}}"`
{{end}}
}
调用文件:
type tplData struct {
tableName string
tableData interface{}
}
func doStuff() {
t, err := template.ParseFiles("templates/struct.tpl")
if err != nil {
errorQuit(err)
}
t = t.Funcs(template.FuncMap{
"makeGoName": makeGoName,
"makeDBName": makeDBName,
})
data := tplData{
tableName: tableName,
tableData: tableInfo,
}
t.Execute(os.Stdout, data)
}
func makeGoName(name string) string {
return name
}
func makeDBName(name string) string {
return name
}
这是一个生成结构样板代码的程序(以防有人想知道我为什么在模板中这样做)。
自定义函数需要在解析模板之前注册,否则解析器将无法判断标识符是否是有效的函数名称。模板被设计为可静态分析,这是对此的要求。
template.New()
创建一个新的、未定义的模板,除了 template.ParseFiles()
函数之外,template.Template
类型(由 New()
返回)还有一个 Template.ParseFiles()
方法,你可以称之为。
类似这样的:
t, err := template.New("struct.tpl").Funcs(template.FuncMap{
"makeGoName": makeGoName,
"makeDBName": makeDBName,
}).ParseFiles("templates/struct.tpl")
当使用
template.ParseFiles()
时,对 template.New()
的调用必须指定正在执行的文件的基本名称。
Template.Execute()
返回 error
,打印它以查看是否没有生成输出,例如:
if err := t.Execute(os.Stdout, data); err != nil {
fmt.Println(err)
}
为模板注册自定义函数并使用
ParseFiles()
时,您需要在实例化并执行模板时指定模板的名称。拨打ParseFiles()
后还需要拨打Funcs()
。
// Create a named template with custom functions
t, err := template.New("struct.tpl").Funcs(template.FuncMap{
"makeGoName": makeGoName,
"makeDBName": makeDBName,
}).ParseFiles("templates/struct.tpl") // Parse the template file
if err != nil {
errorQuit(err)
}
// Execute the named template
err = t.ExecuteTemplate(os.Stdout, "struct.tpl", data)
if err != nil {
errorQuit(err)
}
使用命名模板时,名称是不带目录路径的文件名,例如
struct.tpl
不是templates/struct.tpl
。所以 New()
和 ExecuteTemplate()
中的名称应该是字符串 struct.tpl
。