模板和自定义功能;恐慌:功能未定义 [英] Template and custom function; panic: function not defined

查看:70
本文介绍了模板和自定义功能;恐慌:功能未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 html / template 我想在模板中使用我自己的函数之一。不幸的是,我无法使用go模板的功能图功能。我得到的是以下错误:

Using html/template I am trying to use one of my own functions inside a template. Unfortunately I am unable to use the function map feature of go's templates. All I get is the following error:

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

如下所示( test.go ):

The reduced testcase looks as follows (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 ):

And I have the following simple template (tmpl.html):

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

这是1.1.1。

推荐答案

在解析模板之前,模板函数映射必须由 .Funcs 定义。

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

这篇关于模板和自定义功能;恐慌:功能未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆