go - 模板和自定义功能; panic : function not defined

标签 go

使用 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。

最佳答案

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

关于go - 模板和自定义功能; panic : function not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17843311/

相关文章:

json - 在 Go 中解码时如何识别无效值和未指定的字段?

go - 在 protobuf 文件中使用 google.protobuf.Value 并在结构中使用 go interface{} 字段,反之亦然

python-3.x - 去命名参数

go - 使用指向 Golang 中的结构的指针将方法转换为函数

string - 无论如何要在 Go 中创建以空字符结尾的字符串吗?

戈朗 : calculate how many goroutines are started by worker itself?

go - 我如何使用 channel 来知道循环启动的所有 goroutines 何时完成

go - 导入声明中的空行

go - 如何将多个并发请求分配给 aws lambda 函数?

go - 无法弄清楚为什么这个循环是数据竞争