23

使用html/template我正在尝试在模板中使用我自己的功能之一。不幸的是,我无法使用 go 模板的功能映射功能。我得到的只是以下错误:

% go run test.go
panic: template: tmpl.html:5: function "humanSize" not defined
[...]

简化后的测试用例如下(test.go):

package main

import (
    "html/template"
    "io/ioutil"
    "net/http"
    "strconv"
)

var funcMap = template.FuncMap{
    "humanSize": humanSize,
}
var tmplGet = template.Must(template.ParseFiles("tmpl.html")).Funcs(funcMap)

func humanSize(s int64) string {
    return strconv.FormatInt(s/int64(1000), 10) + " KB"
}

func getPageHandler(w http.ResponseWriter, r *http.Request) {
    files, _ := ioutil.ReadDir(".")
    if err := tmplGet.Execute(w, files); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

func main() {
    http.HandleFunc("/", getPageHandler)
    http.ListenAndServe(":8080", nil)
}

我有以下简单的模板(tmpl.html):

<html><body>
    {{range .}}
    <div>
        <span>{{.Name}}</span>
        <span>{{humanSize .Size}}</span>
    </div>
    {{end}}
</body></html>

这是 1.1.1。

4

2 回答 2

36

IIRC, template functions map must be defined by .Funcs before parsing the template. The below code seems to work.

package main

import (
        "html/template"
        "io/ioutil"
        "net/http"
        "strconv"
)

var funcMap = template.FuncMap{
        "humanSize": humanSize,
}

const tmpl = `
<html><body>
    {{range .}}
    <div>
        <span>{{.Name}}</span>
        <span>{{humanSize .Size}}</span>
    </div>
    {{end}}
</body></html>`

var tmplGet = template.Must(template.New("").Funcs(funcMap).Parse(tmpl))

func humanSize(s int64) string {
        return strconv.FormatInt(s/int64(1000), 10) + " KB"
}

func getPageHandler(w http.ResponseWriter, r *http.Request) {
        files, err := ioutil.ReadDir(".")
        if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
        }

        if err := tmplGet.Execute(w, files); err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
        }
}

func main() {
        http.HandleFunc("/", getPageHandler)
        http.ListenAndServe(":8080", nil)
}
于 2013-07-24T20:22:16.653 回答
1

解决方案是在 @user321277 建议的函数 New() 和 Parse‌​Files() 中使用相同的名称

var tmplGet = template.Must(template.New("base.html").Funcs(funcMap).Parse‌​Files("tmpl/base.htm‌​l", "tmpl/get.html"))
于 2018-01-19T07:36:36.010 回答