Golang:帮助将函数注册到模板中。

huangapple go评论78阅读模式
英文:

Golang: Help registering a function into templates

问题

我正在尝试在我的模板中添加一个函数来“人性化”输出,但似乎我做错了什么,因为我得到了这个错误:

panic: template: dashboard.tmpl:192: 函数"humanizeTime"未定义

func renderTemplate(w http.ResponseWriter, name string, data map[string]interface{}) error {
// 模板函数
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("渲染模板时出错:%s", err.Error())
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return errors.New("尝试渲染模板时出错")
}
return nil

}

添加了以下内容:
我在init()函数中定义并加载了我的模板映射:

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

我只是将我的定义更改为:

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

但仍然不起作用,我仍然得到相同的错误:未定义。

请问有人可以帮我解决这个问题吗?谢谢。

英文:

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.

答案1

得分: 1

在将函数附加到模板后,您需要调用Parse()方法。我不知道您的模板映射是如何定义的,但是假设它是一个模板文本的映射,调用应该像这样:

tmpl := template.New(templateName).Funcs(template.FuncMap{
    ....  
}).Parse(Templates[name+".tmpl"])

如果Templates包含已解析的模板,则需要在解析它们时附加函数。

英文:

You need to call Parse() on the template after attaching the funcs to it. I don't know how your template map is being defined, but assuming it's a map of template texts, the call should look like this:

tmpl := template.New(templateName).Funcs(template.FuncMap{
        ....  
        }).Parse(Templates[name+".tmpl"])

If Templates contains parsed templates, you need to attach the function when you're parsing them.

答案2

得分: 0

好的,以下是翻译好的内容:

好的,最终这个解决方案对我的情况有效,基于Not_a_Golfer的帮助:

for _, layout := range layouts {
    t := template.New("t").Funcs(templateFuncs)
    Templates[filepath.Base(layout)], err = t.ParseFiles(layouts...)
    if err != nil {
        panic(err)
    }
}
英文:

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

huangapple
  • 本文由 发表于 2015年6月7日 01:50:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/30685872.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定