How to Use Template Inheritance and Layouts in Go

Web
Go lacks native template inheritance; use {{define}} and {{template}} to manually compose reusable layout blocks.

Go's standard library does not support template inheritance or layouts; you must manually compose templates using {{template}} and {{define}} directives. Create a base template with named blocks, then define child templates that reference those blocks to reuse structure.

// base.html
{{define "base"}}
<!DOCTYPE html>
<html>
<head><title>{{.Title}}</title></head>
<body>
{{template "content" .}}
</body>
</html>
{{end}}

// page.html
{{define "content"}}
<h1>{{.Heading}}</h1>
<p>{{.Body}}</p>
{{end}}

// main.go
package main

import (
	"html/template"
	"os"
)

func main() {
	tmpl := template.Must(template.ParseFiles("base.html", "page.html"))
	data := map[string]string{"Title": "Home", "Heading": "Welcome", "Body": "Hello World"}
	tmpl.ExecuteTemplate(os.Stdout, "base", data)
}