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