模板和自定义功能; 恐慌:功能未定义

20 go

使用html/template我试图在模板中使用我自己的一个函数.不幸的是我无法使用go模板的功能映射功能.我得到的是以下错误:

% go run test.go
panic: template: tmpl.html:5: function "humanSize" not defined
[...]
Run Code Online (Sandbox Code Playgroud)

简化的测试用例如下(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)
}
Run Code Online (Sandbox Code Playgroud)

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

<html><body>
    {{range .}}
    <div>
        <span>{{.Name}}</span>
        <span>{{humanSize .Size}}</span>
    </div>
    {{end}}
</body></html>
Run Code Online (Sandbox Code Playgroud)

这是1.1.1.

zzz*_*zzz 33

IIRC,模板函数映射必须.Funcs在解析模板之前定义.以下代码似乎有效.

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)
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.在解析模板之前,您需要添加函数映射并不明显; 我在文档中找不到.我最终得到了`var tmplGet = template.Must(template.New("base.html").Funcs(funcMap).ParseFiles("tmpl/base.html","tmpl/get.html"))`,因为我使用嵌套模板.另一个问题是`New()`需要与"顶级"模板具有相同的基本名称. (23认同)