1// Copyright 2012 The Go Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style 3// license that can be found in the LICENSE file. 4 5package template_test 6 7import ( 8 "log" 9 "os" 10 "strings" 11 12 "github.com/alecthomas/template" 13) 14 15// This example demonstrates a custom function to process template text. 16// It installs the strings.Title function and uses it to 17// Make Title Text Look Good In Our Template's Output. 18func ExampleTemplate_func() { 19 // First we create a FuncMap with which to register the function. 20 funcMap := template.FuncMap{ 21 // The name "title" is what the function will be called in the template text. 22 "title": strings.Title, 23 } 24 25 // A simple template definition to test our function. 26 // We print the input text several ways: 27 // - the original 28 // - title-cased 29 // - title-cased and then printed with %q 30 // - printed with %q and then title-cased. 31 const templateText = ` 32Input: {{printf "%q" .}} 33Output 0: {{title .}} 34Output 1: {{title . | printf "%q"}} 35Output 2: {{printf "%q" . | title}} 36` 37 38 // Create a template, add the function map, and parse the text. 39 tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText) 40 if err != nil { 41 log.Fatalf("parsing: %s", err) 42 } 43 44 // Run the template to verify the output. 45 err = tmpl.Execute(os.Stdout, "the go programming language") 46 if err != nil { 47 log.Fatalf("execution: %s", err) 48 } 49 50 // Output: 51 // Input: "the go programming language" 52 // Output 0: The Go Programming Language 53 // Output 1: "The Go Programming Language" 54 // Output 2: "The Go Programming Language" 55} 56