github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/text/template/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 package template_test 6 7 import ( 8 "github.com/shogo82148/std/log" 9 "github.com/shogo82148/std/os" 10 "github.com/shogo82148/std/strings" 11 "github.com/shogo82148/std/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 // 最初に、関数を登録するためのFuncMapを作成します。 19 funcMap := template.FuncMap{ 20 // 名前 "title" は、テンプレートテキスト内で関数が呼ばれる名前です。 21 "title": strings.Title, 22 } 23 24 // 関数をテストするためのシンプルなテンプレート定義。 25 // 入力テキストをいくつかの方法で出力します: 26 // - オリジナル 27 // - タイトルケース 28 // - タイトルケースにした後に %q で出力 29 // - %q で出力した後にタイトルケースにします。 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 // テンプレートを作成し、関数マップを追加し、テキストを解析します。 38 tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText) 39 if err != nil { 40 log.Fatalf("parsing: %s", err) 41 } 42 43 // テンプレートを実行して出力を確認します。 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 }