Skip to content

Instantly share code, notes, and snippets.

@suntong
Last active June 17, 2022 07:52
Show Gist options
  • Save suntong/51e3a5c9deadba757ff0a11fd13c5826 to your computer and use it in GitHub Desktop.
Save suntong/51e3a5c9deadba757ff0a11fd13c5826 to your computer and use it in GitHub Desktop.
Go template FuncMap example, working

Url

https://play.golang.org/p/EmDhbkLSvD

Changes

Add back var myFuncMap.

Output

Input: "the go programming language"
  Output 0: The Go Programming Language
  Output 1: "The Go Programming Language"
  Output 2: "The Go Programming Language"
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"log"
"os"
"strings"
"text/template"
)
type MyTmpl struct {
*template.Template
}
type MyFuncMap map[string]interface{}
// First we create a FuncMap with which to register the function.
var myFuncMap = MyFuncMap{
// The name "title" is what the function will be called in the template text.
"title": strings.Title,
}
func NewTemplate(tname string) *MyTmpl {
return &MyTmpl{template.New(tname)}
}
func (t *MyTmpl) FuncDefs() template.FuncMap {
return template.FuncMap(myFuncMap)
}
// This example demonstrates a custom function to process template text.
// It installs the strings.Title function and uses it to
// Make Title Text Look Good In Our Template's Output.
func main() {
// A simple template definition to test our function.
// We print the input text several ways:
// - the original
// - title-cased
// - title-cased and then printed with %q
// - printed with %q and then title-cased.
const templateText = `
Input: {{printf "%q" .}}
Output 0: {{title .}}
Output 1: {{title . | printf "%q"}}
Output 2: {{printf "%q" . | title}}
`
// Create a template, add the function map,
// tmpl := NewTemplate("titleTest").Funcs(template.FuncMap(myFuncMap))
tmpl0 := NewTemplate("titleTest")
tmpl := tmpl0.Funcs(tmpl0.FuncDefs())
// parse the text.
tmpl, err := tmpl.Parse(templateText)
if err != nil {
log.Fatalf("parsing: %s", err)
}
// Run the template to verify the output.
err = tmpl.Execute(os.Stdout, "the go programming language")
if err != nil {
log.Fatalf("execution: %s", err)
}
// Output:
// Input: "the go programming language"
// Output 0: The Go Programming Language
// Output 1: "The Go Programming Language"
// Output 2: "The Go Programming Language"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment