当我尝试访问传递给模板的函数时出现错误:
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("").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)
}
关于templates - Golang 模板(并将函数传递给模板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35550326/