drasebt1835 2016-02-22 09:45
浏览 49
已采纳

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?

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}}
}

Calling file:

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).

  • 写回答

1条回答 默认 最新

  • dtxf759200 2016-02-22 10:03
    关注

    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.

    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.

    Something like this:

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

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

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀