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