How to easily make nested templates (Go)

November 10, 2017

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)

Show comments
Written on 10 November 2017. Categories: coding, golang.

«Odd one out 
Painting from computer-generated primitives»