Golang 模板(并将函数传递给模板) [英] Golang templates (and passing funcs to template)

查看:29
本文介绍了Golang 模板(并将函数传递给模板)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm getting an error when I try and access a function I'm passing to my template:

Error: template: struct.tpl:3: function "makeGoName" not defined

谁能告诉我我做错了什么?

Can anyone please let me know what I'm doing wrong?

模板文件(struct.tpl):

Template file (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
}

这是用于生成结构样板代码的程序(以防有人想知道我为什么要在模板中这样做).

This is for a program that generates struct boilerplate code (in case anyone is wondering why I'm doing that in my template).

推荐答案

在解析模板之前需要注册自定义函数,否则解析器将无法判断标识符是否是有效的函数名称.模板被设计为可静态分析的,这是对模板的要求.

Custom functions need to be registered before parsing the templates, else the parser would not be able to tell whether an identifier is a valid function name or not. Templates are designed to be statically analyzable, and this is a requirement to that.

您可以首先使用 template.New()<创建一个新的未定义模板/code>,除了 template.ParseFiles() 功能template.Template 类型(由 New() 返回)也有一个 Template.ParseFiles() 方法,你可以调用它.

You can first create a new, undefined template with template.New(), and besides the template.ParseFiles() function, the template.Template type (returned by New()) also has a Template.ParseFiles() method, you can call that.

像这样:

t, err := template.New("").Funcs(template.FuncMap{
    "makeGoName": makeGoName,
    "makeDBName": makeDBName,
}).ParseFiles("templates/struct.tpl")

请注意,template.ParseFiles() 函数还在后台调用了 template.New(),将第一个文件的名称作为模板名称传递.

Note that the template.ParseFiles() function also calls template.New() under the hood, passing the name of the first file as the template name.

还有 Template.Execute()返回一个 error,打印出来看看是否没有输出,例如:

Also Template.Execute() returns an error, print that to see if no output is generated, e.g.:

if err := t.Execute(os.Stdout, data); err != nil {
    fmt.Println(err)
}

这篇关于Golang 模板(并将函数传递给模板)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆