Template glob funcs
This is an example Go program which demonstrates adding custom
functions with Funcs
and multiple templates with
ParseGlob
at the same time. It also demonstrates how to get
array and other values within a range
loop in the template.
package main import ( "fmt" "os" "text/template" ) var tmplDir = "/home/ben/lemoda/go/template-glob-funcs/" func GetArray(counts []int64, id int64) int64 { return counts[id] } func main() { numbers := []int64{0, 1, 2, 3, 4} data := []int64{0, 9, 18, 27, 36} var input struct { Data []int64 Numbers []int64 Multiplier int64 } input.Numbers = numbers input.Data = data input.Multiplier = 9 templates := template.New("example") customFunctions := template.FuncMap{"GetArray": GetArray} templates.Funcs(customFunctions) template.Must(templates.ParseGlob(tmplDir + "*.txt")) t := templates.Lookup("times-table.txt") err := t.Execute(os.Stdout, input) if err != nil { fmt.Printf("Error excuting template: %s\n", err.Error()) } }
The template looks like this:
{{- $array := .Data}} {{- $mult := .Multiplier}} {{- range $_, $number := .Numbers}}{{.}} × {{$mult}} = {{GetArray $array .}} {{end -}}
The output of the example looks like this:
0 × 9 = 0 1 × 9 = 9 2 × 9 = 18 3 × 9 = 27 4 × 9 = 36
Copyright © Ben Bullock 2009-2024. All
rights reserved.
For comments, questions, and corrections, please email
Ben Bullock
(benkasminbullock@gmail.com).
/
Privacy /
Disclaimer