3
拆分字符串我嘗試使用template.FuncMap但有嚴重錯誤golang - 如何在模板
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}}
謝謝。
您錯過了重要的一點(錯誤原因):在'nil'的'tpl'上訪問'Funcs'。 – nemo
@Tyler Egeto,在實際的代碼中,我有輸出錯誤。我確定在「a.html」Split功能中有一些操作,因爲如果我評論它的代碼,它工作的很好。 – leiyonglin
當您在模板中刪除Split功能時,它的工作原因是因爲解析器不再尋找未定義的Func。如提到的尼莫,我可以更清楚。我正在更新一個例子。 –