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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.