Golang模板(并将func传递给模板)
发布时间:2020-12-16 09:27:27 所属栏目:大数据 来源:网络整理
导读:当我尝试访问我传递给我的模板的函数时,我收到错误: Error: template: struct.tpl:3: function "makeGoName" not defined 任何人都可以让我知道我做错了什么? 模板文件(struct.tpl): type {{.data.tableName}} struct { {{range $key,$value := .data.tab
当我尝试访问我传递给我的模板的函数时,我收到错误:
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 } 这是一个生成结构样板代码的程序(如果有人想知道为什么我在我的模板中这样做). 解决方法
在解析模板之前需要注册自定义函数,否则解析器将无法判断标识符是否是有效的函数名.模板设计为静态可分析,这是一个要求.
您可以先使用 像这样的东西: t,err := template.New("").Funcs(template.FuncMap{ "makeGoName": makeGoName,}).ParseFiles("templates/struct.tpl") 请注意,template.ParseFiles()函数还会调用template.New(),并将第一个文件的名称作为模板名称传递.
if err := t.Execute(os.Stdout,data); err != nil { fmt.Println(err) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |