英文:
golang - how to split string in template
问题
我尝试使用template.FuncMap,但出现了恐慌错误。
恐慌错误:运行时错误:无效的内存地址或空指针解引用
代码:
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
//我想要分割tags并进行循环
{{$arr := Split .Tags ","}}
{{range $k, $v := $arr}}
<a href="{{$v}}">{{$v}}</a>
{{end}}
谢谢。
英文:
I try to use template.FuncMap but there are panic error
panic: runtime error: invalid memory address or nil pointer dereference
code:
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}}
Thanks.
答案1
得分: 3
你正在忽略template.ParseFiles
返回的错误,这可能会告诉你问题所在。当解析模板时,ParseFiles
可能会抛出错误,因为函数Split
未定义。永远不要忽略错误。
编辑
要使其工作,可以像这样操作:
tplFuncMap = make(template.FuncMap)
tplFuncMap["Split"] = Split
tmpl, err = template.New("").Funcs(tplFuncMap).ParseFiles("a.html", "b.html")
不同之处在于在解析模板之前定义了FuncMap
。
英文:
You are ignoring the error returned by template.ParseFiles
, that will probably tell you your problem. ParseFiles is probably throwing an error because the function Split
isn't defined when you parse the template. Never ignore errors.
Edit
To make it work, do something like this:
tplFuncMap = make(template.FuncMap)
tplFuncMap["Split"] = Split
tmpl, err = template.New("").Funcs(tplFuncMap).ParseFiles("a.html", "b.html")
The difference is that the FuncMap
is defined before the templates are parsed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论