我尝试使用template.FuncMap但出现紧急错误
panic: runtime error: invalid memory address or nil pointer dereference
码:
type Article struct{
Id int
Title string
Tags string
}
var (
tplFuncMap template.FuncMap
)
func main() {
article := &Article{Id:1, Title:"hello world", Tags:"golang,javascript"}
tplFuncMap = make(template.FuncMap)
tplFuncMap["Split"] = Split
tpl, _ := template.ParseFiles("a.html", "b.html")
tpl = tpl.Funcs(tplFuncMap)
tpl.Execute(os.Stdout, article)
}
func Split(s string, d string) []string {
arr := strings.Split(s, d)
return arr
}
a.html
//i want to split tags and range
{{$arr := Split .Tags ","}}
{{range $k, $v := $arr}}
<a href="{{$v}}">{{$v}}</a>
{{end}}
谢谢。
您正在忽略所返回的错误template.ParseFiles
,它可能会告诉您您的问题。ParseFiles可能会引发错误,因为Split
解析模板时未定义函数。永远不要忽略错误。
编辑
要使其工作,请执行以下操作:
tplFuncMap = make(template.FuncMap)
tplFuncMap["Split"] = Split
tmpl, err = template.New("").Funcs(tplFuncMap).ParseFiles("a.html", "b.html")
区别在于在FuncMap
解析模板之前已定义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句