Template and custom function; panic: function not defined

后端 未结 2 517
无人及你
无人及你 2021-02-04 01:39

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

相关标签:
2条回答
  • 2021-02-04 02:00

    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)
    }
    
    0 讨论(0)
  • 2021-02-04 02:14

    The solution is to have same names in the function New() and Parse‌​Files() a suggested by @user321277

    var tmplGet = template.Must(template.New("base.html").Funcs(funcMap).Parse‌​Files("tmpl/base.htm‌​l", "tmpl/get.html"))
    
    0 讨论(0)
提交回复
热议问题