当我尝试使用Funcs
和FuncMap
. 以下代码按预期工作:
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"
但是当我尝试将模板放入文件时,它不起作用(Execute()
说:)"alex" is an incomplete or empty template
:
t, _ := template.New("alex").Funcs(funcMap).ParseFiles("template.html")
使用模板.html:
{{label \"alex\"}}
知道为什么吗?这是一个错误吗?有没有更简单的方法在模板中使用方法/函数?