I have several go templates. The below examples are oversimplified, but it states my idea correctly. For example, I have
{{ define "div-block" }}
<div style="display:block">
.....
</div>
{{ end }}
Now I want to transfer any other template inside div-block
when using it, so that I could put anything inside div. E.g:
{{ template "div-block" . }}
{{ template "header" }}
{{ end }}
{{ template "div-block" . }}
<ul>
<li>1</li>
</ul>
{{ end }}
Where "header" is some other template.
Which is the the right way to do this with go template? Is it possible to do it with custom function? Is it possible to make custom actions
in go template? (actions can have end
statement and therefore the body, while functions are not)
You can use nested template in go template.
divBlock := `<div>Hello div
{{block "header" .}} {{.}} {{end}}
</div>`
header := `<header>Hello Header</header>`
divTempl, err := template.New("master").Parse(divBlock)
if err != nil {
log.Fatal(err)
}
if err := divTempl.Execute(os.Stdout, header); err != nil {
log.Fatal(err)
}
Go-playground link: https://play.golang.org/p/K36l3bn5753
Or
You can use if statement. Check whether there is some template, then append, otherwise empty.
const (
divBlock = `<div style="display:block">
.....
{{if "injectedTmpl"}}{{.}}{{end}}
</div>`
)
injectedTmpl := `<header>Hello Header</header>`
divTmpl, err := template.New("div").Parse(divBlock)
if err != nil {
log.Fatal(err)
}
if err := divTmpl.Execute(os.Stdout, injectedTmpl); err != nil {
log.Fatal(err)
}
Go-playground link: https://play.golang.org/p/pZaqXtCHHAL