templates - Golang 模板(并将函数传递给模板)

标签 templates go go-templates

当我尝试访问传递给模板的函数时出现错误:

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/

相关文章:

http - 无法通过 Go API 在客户端中设置 cookie

go - 如何将接口(interface)转换为接口(interface) slice ?

regex - 去替换所有字符串

performance - 我应该在每个 http 请求上调用 template.ParseFiles(...) 还是只从主函数调用一次?

go - 如何修剪 Go 模板中的空行?

c++ - 由于意外的模板参数类型推导而导致的无限递归

c++ - std::enable_if 更改成员 *variable* 声明/类型

c++ - 从函数模板参数自动推断对容器的元素类型

python - 使用 Python/Flask 进行 MySQL 查询

templates - 具体范围示例