Template Define Blocks Reuse

Declare reusable blocks with text/template define and render them through template actions, keeping one row layout across several records.

GoData Integrity

Code

gosnippet
36 lines
package main

import (
	"fmt"
	"os"
	"text/template"
)

type Server struct {
	Name string
	Port int
}

func main() {
	const layout = `{{define "row"}}{{printf "%-10s %5d" .Name .Port}}{{end -}}
{{range .}}{{template "row" .}}
{{end}}`

	servers := []Server{{Name: "api", Port: 8080}, {Name: "metrics", Port: 9090}}

	// define blocks are parsed once and reused by every template action
	tmpl, err := template.New("servers").Parse(layout)
	if err != nil {
		fmt.Println("parse failed:", err)
		return
	}
	if err := tmpl.Execute(os.Stdout, servers); err != nil {
		fmt.Println("execute failed:", err)
		return
	}

	// a named block can also run on its own
	if err := tmpl.ExecuteTemplate(os.Stdout, "row", Server{Name: "worker", Port: 7000}); err != nil {
		fmt.Println("block failed:", err)
	}
}

How it works

Template Define Blocks Reuse reduces to the function main.

Nothing falls through silently — 2 checkpoints test err != nil on the way through.

Caveats

  • Self-contained — no imports beyond what the runtime already provides.

Using it

Entry signature: func main()

Running the file prints labeled results such as parse failed:, execute failed:, block failed: — each operation’s effect is visible in the output.

Key statements

{{range .}}{{template "row" .}}
if err != nil {
fmt.Println("parse failed:", err)
return
}

Interactive Tools for This Topic

FAQ

What does Template Define Blocks Reuse print when run?
Execute the whole file; each printed line is prefixed with a label like `parse failed:`, `execute failed:`, `block failed:`.