dongou3286 2015-06-06 17:50
浏览 70
已采纳

Golang:帮助将功能注册到模板中

I'm trying to add to my templates a function to "humanize"(https://gowalker.org/github.com/dustin/go-humanize) the output, but seems something I'm doing wrong because I'm getting this error:

panic: template: dashboard.tmpl:192: function "humanizeTime" not defined

func renderTemplate(w http.ResponseWriter, name string, data map[string]interface{}) error {
    //functions for templates
    templateFuncs := template.FuncMap{
        "humanizeTime": func(t time.Time) string {
            return humanize.Time(t)
        },
    }
    tmpl := Templates[name+".tmpl"].Funcs(templateFuncs)
    w.Header().Set("Content-Type", "text/html; charset=utf-8")

    err := tmpl.ExecuteTemplate(w, name, data)
    if err != nil {
        log.Printf("Error rendering template: %s", err.Error())
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return errors.New("Error trying to render template")
    }
    return nil
}

Added: I am defining and loading on init() my templates Map:

var Templates      map[string]*template.Template

if Templates == nil {
    Templates = make(map[string]*template.Template)
}
layouts, err := filepath.Glob("templates/*.tmpl")
if err != nil {
    panic(err)
}
for _, layout := range layouts {
    Templates[filepath.Base(layout)] = template.Must(template.ParseFiles(layouts...))
}

I just change my definition to:

for _, layout := range layouts {
    Templates[filepath.Base(layout)] = template.Must(template.ParseFiles(layouts...)).Funcs(templateFuncs)
}

But doesn't work yet, I got the same error: not defined.

Please could somebody give me a hand with that? Thanks.

  • 写回答

2条回答 默认 最新

  • duanhuihui2705 2015-06-09 13:33
    关注

    Ok, finally this solution works done for my case, based on Not_a_Golfer help:

    for _, layout := range layouts {
        t := template.New("t").Funcs(templateFuncs)
        Templates[filepath.Base(layout)], err = t.ParseFiles(layouts...)
        if err != nil {
            panic(err)
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码