去模板功能 [英] Go template function

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

问题描述

当我尝试使用 Funcs FuncMap 时,它发现Go模板有一个奇怪的地方。以下代码按预期工作:

  buffer:= bytes.NewBufferString()

funcMap := template.FuncMap {
label:strings.Title,
}
$ bt,_:= template.New(alex)。Funcs(funcMap).Parse ({{label \alex\}})

t.Execute(buffer,)

return string(buffer.Bytes()) // => Alex

但是,当我尝试将模板放入文件时,它不起作用( Execute()说:alex是一个不完整或空的模板):

  t,_:= template.New(alex)。Funcs(funcMap).ParseFiles(template.html)



使用template.html:

  {{label \alex\}} 

任何想法为什么?这是一个错误?是否有更简单的方法在模板中使用方法/函数?

解决方案

ParseFiles可能使用更好的文档。模板对象可以有多个模板,每个模板都有一个名称。如果你看看ParseFiles的实现,你会发现它使用 filename 作为模板对象的模板名称。因此,请将您的文件命名为与模板对象相同的名称(可能通常不太实用),否则请使用ExecuteTemplate而不是只执行。


It noticed a weird thing with Go templates when I try to use Funcs and FuncMap. The following code works as expected:

buffer := bytes.NewBufferString("")

funcMap := template.FuncMap{
    "label": strings.Title,
}

t, _ := template.New("alex").Funcs(funcMap).Parse("{{label \"alex\"}}") 

t.Execute(buffer, "")

return string(buffer.Bytes()) //=> "Alex"

But when I try to put the template in a file, it does not work (Execute() says: "alex" is an incomplete or empty template):

t, _ := template.New("alex").Funcs(funcMap).ParseFiles("template.html") 

With template.html:

{{label \"alex\"}}

Any idea why ? Is this a bug ? Are there simpler ways to use methods/functions in templates ?

解决方案

ParseFiles could probably use better documentation. A template object can have multiple templates in it and each one has a name. If you look at the implementation of ParseFiles, you see that it uses the filename as the template name inside of the template object. So, name your file the same as the template object, (probably not generally practical) or else use ExecuteTemplate instead of just Execute.

这篇关于去模板功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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