Zack Scholl

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.

package main

import (

type View struct {
    Title   string
    Content string

func main() {

    header := `
{{define "header"}}
         <title>{{ $.Title }}</title>

    page := `
This line should not show
{{define "indexPage"}}
    {{template "header" .}}
        <h1>{{ .Content }}</h1>

    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)