Post

Go funcMaps

How to use template.FuncMap in Go to register custom functions (like string uppercasing and trimming) for use inside Go templates.

This program demonstrates template.FuncMap in Go, which allows you to register custom functions and make them available inside templates. Here, two functions are registered: uc for uppercasing strings (using strings.ToUpper) and ft for extracting the first three characters. These can then be called directly in .gohtml template files using the or syntax.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main

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

var tpl *template.Template

func firstThree(s string) string  {
	s = strings.TrimSpace(s)
	s = s[:3]
	return s
}

var fm = template.FuncMap{
	"uc": strings.ToUpper,
	"ft": firstThree,
}

func init() {
	fmt.Println("Initializing ...")
	// tpl = template.Must(template.ParseGlob("*.gohtml"))
	//  to incorporate some extra function into template object
	tpl = template.Must(template.New("").Funcs(fm).ParseGlob("*.gohtml"))
}

type sage struct {
	Name  string
	Motto string
}

func main()  {
	b := sage{
		Name: "Buddha",
		Motto: "The belief of no beliefs",
	}

	g := sage{
		Name: "Gandhi",
		Motto: "Be the change",
	}

	j := sage{
		Name: "Jesus",
		Motto: "Love!",
	}

	sages := []sage{b, g, j}

	data := struct{
		Wisdom []sage
	}{
		Wisdom: sages,
	}

	err := tpl.ExecuteTemplate(os.Stdout, "funcintpl.gohtml", data)
	if err != nil {
		log.Fatalln(err)
	}


}

This post is licensed under CC BY 4.0 by the author.