Zack Scholl

zack.scholl@gmail.com

Nesting templates in Golang

 / #golang #tutorial 

A small snippet for making nested templates in Golang.

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

 1package main
 2
 3import (
 4    "bytes"
 5    "fmt"
 6    "log"
 7    "text/template"
 8)
 9
10type View struct {
11    Title   string
12    Content string
13}
14
15func main() {
16
17    header := `
18{{define "header"}}
19     <head>
20         <title>{{ $.Title }}</title>
21     </head>
22{{end}}`
23
24    page := `
25This line should not show
26{{define "indexPage"}}
27    <html>
28    {{template "header" .}}
29    <body>
30        <h1>{{ .Content }}</h1>
31    </body>
32    </html>
33{{end}}`
34
35    view := View{Title: "some title", Content: "some content"} // Here we try to set which page to view as content
36    t := template.New("basic")
37    t = template.Must(t.Parse(header))
38    t = template.Must(t.Parse(page))
39    var tpl bytes.Buffer
40    err := t.ExecuteTemplate(&tpl, "indexPage", view)
41    if err != nil {
42        log.Println("executing template:", err)
43    }
44    fmt.Println(tpl.String())
45}