我遇到了自定义函数和 Go 模板无法正常工作的问题。 这是一个重新创建的示例:
package main
import (
"os"
"text/template"
"time"
)
func formatDate(t time.Time) string {
if t.IsZero() {
return ""
}
return t.Format("2006-01-02")
}
func main() {
someTmpl := "<div> {{FormatDate .Date}} </div>"
funcMap := template.FuncMap{
"FormatDate": formatDate,
}
date := time.Now()
tmpl := template.Must(template.New("").Funcs(funcMap).Parse(someTmpl))
tmpl.Execute(os.Stdout, date)
}
(也可以找到这里) 对于游乐场,它只打印出
函数“FormatDate”未定义
非常感谢任何帮助!
编辑: 我让它在我的示例中工作here。不幸的是,在我的生产代码中仍然找不到该功能。该代码如下所示:
func formatDate(t time.Time) string {
if t.IsZero() {
return ""
}
return t.Format("2006-01-02")
}
fileParts := strings.Split(t.templateFilePath,string(os.PathSeparator))
fileName := fileParts[len(fileParts)-1]
funcMap := template.FuncMap{
"FormatDate": formatDate,
}
tmpl := template.Must(template.New(fileName).Funcs(funcMap).ParseFiles(t.templateFilePath))
t 是一个只有“templateFilePath”字段作为字符串的结构体。
好吧,原因还是——坐在屏幕前。我过于专注于一个函数,没有意识到它实际上是一个不同的、非常相似的函数,引发了错误。 重复代码的经典案例 - 语言中没有错误。
好吧,原因还是——坐在屏幕前。我过于专注于一个函数,没有意识到它实际上是一个不同的、非常相似的函数,引发了错误。 重复代码的经典案例 - 语言中没有错误。