How to extend a template in go?

巧了我就是萌 提交于 2020-12-07 04:51:08

问题


Here is the problem: There are several articles on each page's content section and I'd like to insert a likebar template below each article.

So the base.tmpl is like:

<html>
  <head>    
    {{template "head.tmpl" .}}
  </head>
  <body>    
    {{template "content.tmpl" .}}   
   </body>
</html>

and in article.tmpl I want to have :

    {{define "content"}}    
          <div>article 1 
             {{template "likebar.tmpl" .}} 
          </div> 
          <div>article 2
             {{template "likebar.tmpl" .}} 
         </div>
       ... //these divs are generated dynamically
    {{end}}

How can I achieve this with html/template? I have tried to insert a {{template "iconbar" .}} in base.tmpl and then nested {{template "likebar.tmpl" .}} inside {{define "content" but it failed with:

Template File Error: html/template:base.tmpl:122:12: no such template "likebar.tmpl"


回答1:


You can only include / insert associated templates.

If you have multiple template files, use template.ParseFiles() or template.ParseGlob() to parse them all, and the result template will have all the templates, already associated, so they can refer to each other.

If you do use the above functions to parse your templates, then the reason why it can't find likebar.tmpl is because you are referring to it by an invalid name (e.g. missing folder name).

When parsing from string source, you may use the Template.Parse() method, which also associates nested templates to the top level template.

See these 2 working examples:

func main() {
    t := template.Must(template.New("").Parse(templ1))
    if err := t.Execute(os.Stdout, nil); err != nil {
        panic(err)
    }

    t2 := template.Must(template.New("").Parse(templ2))
    template.Must(t2.Parse(templ2Like))
    if err := t2.Execute(os.Stdout, nil); err != nil {
        panic(err)
    }
}

const templ1 = `Base template #1
And included one: {{template "likebar"}}
{{define "likebar"}}I'm likebar #1.{{end}}
`

const templ2 = `Base template #2
And included one: {{template "likebar"}}
`

const templ2Like = `{{define "likebar"}}I'm likebar #2.{{end}}`

Output (try it on the Go Playground):

Base template #1
And included one: I'm likebar #1.

Base template #2
And included one: I'm likebar #2.


来源:https://stackoverflow.com/questions/40714378/how-to-extend-a-template-in-go

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!