Custom Template Functions With FuncMap

Register helper functions on a FuncMap so templates call them through pipelines, keeping width padding and casing rules out of application code.

GoCli Tooling

Code

gosnippet
30 lines
package main

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

func main() {
	// FuncMap:注册自定义函数,模板里通过管道调用
	funcs := template.FuncMap{
		"upper": strings.ToUpper,
		"pad": func(width int, s string) string {
			return fmt.Sprintf("%-*s", width, s)
		},
	}
	tpl := template.Must(template.New("report").Funcs(funcs).Parse(
		`{{ range . }}{{ pad 10 .Name }} x{{ .Qty }} @ {{ upper .Unit }}{{ "\n" }}{{ end }}`))

	items := []struct {
		Name string
		Qty  int
		Unit string
	}{{"widget", 3, "pcs"}, {"bolt", 40, "kg"}}

	if err := tpl.Execute(os.Stdout, items); err != nil {
		panic(err)
	}
}

What the code does

Custom Template Functions With FuncMap comes down to the function main.

Every err != nil branch (1 site) calls panic(err) — the run stops at the first failure instead of continuing in a broken state.

What to watch for

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Statements that matter

return fmt.Sprintf("%-*s", width, s)

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
It stops. The one `if err != nil` branch ends in `panic(err)` — nothing continues past a failed call.
How do you run Custom Template Functions With FuncMap?
The file is self-contained: run it directly, no dependencies to install beforehand.