/software
📝 Nesting templates in Go
This is a nice code snippet for understanding the Go template nesting. I refer to this time to time and I thought I’d put it here in case anyone else needed help with it.
https://play.golang.org/p/OVkruYsBVV
package main
import (
"bytes"
"fmt"
"log"
"text/template"
)
type View struct {
Title string
Content string
}
func main() {
header := `
{{define "header"}}
<head>
<title>{{ $.Title }}</title>
</head>
{{end}}`
page := `
This line should not show
{{define "indexPage"}}
<html>
{{template "header" .}}
<body>
<h1>{{ .Content }}</h1>
</body>
</html>
{{end}}`
view := View{Title: "some title", Content: "some content"} // Here we try to set which page to view as content
t := template.New("basic")
t = template.Must(t.Parse(header))
t = template.Must(t.Parse(page))
var tpl bytes.Buffer
err := t.ExecuteTemplate(&tpl, "indexPage", view)
if err != nil {
log.Println("executing template:", err)
}
fmt.Println(tpl.String())
}