golang – how to split string in template

huangapple go评论68阅读模式
英文:

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 := &amp;Article{Id:1, Title:&quot;hello world&quot;, Tags:&quot;golang,javascript&quot;}
    tplFuncMap =  make(template.FuncMap)
    tplFuncMap[&quot;Split&quot;] = Split
    tpl, _ := template.ParseFiles(&quot;a.html&quot;, &quot;b.html&quot;)
    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 &quot;,&quot;}}
{{range $k, $v := $arr}}
    &lt;a href=&quot;{{$v}}&quot;&gt;{{$v}}&lt;/a&gt;
{{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[&quot;Split&quot;] = Split  
tmpl, err = template.New(&quot;&quot;).Funcs(tplFuncMap).ParseFiles(&quot;a.html&quot;, &quot;b.html&quot;)

The difference is that the FuncMap is defined before the templates are parsed.

huangapple
  • 本文由 发表于 2013年11月5日 00:02:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/19771787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定