11

テンプレートに渡す関数にアクセスしようとすると、エラーが発生します。

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
}

これは、struct ボイラープレート コードを生成するプログラム用です (テンプレートでなぜそれを行っているのか疑問に思われる場合に備えて)。

4

2 に答える 2

22

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)
}
于 2016-02-22T10:03:43.303 に答える