Last active
December 15, 2015 08:19
-
-
Save kwmt/5230072 to your computer and use it in GitHub Desktop.
https://github.com/kwmt/golangwiki/blob/master/src/pkg/text/template/exampletemplate_func.go のコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// まず、FuncMapでカスタム関数名と処理したい関数を登録します。 | |
funcMap := template.FuncMap{ | |
// "title"はテンプレートでコールされる関数名となります。 | |
"title": strings.Title, | |
} | |
// 先ほどの関数をテストするために、シンプルなテンプレートを定義します。 | |
// 私たちはいくつかの方法で入力されたテキストを表示します: | |
// - オリジナルテキスト | |
// - "title"をコール | |
// - "title"をコールした後、%qを使って表示する | |
// - %qを使って表示した後、"ttitle"をコール | |
const templateText = ` | |
Input: {{printf "%q" .}} | |
Output 0: {{title .}} | |
Output 1: {{title . | printf "%q"}} | |
Output 2: {{printf "%q" . | title}} | |
` | |
// テンプレート作成し、関数マップを追加し、テキストをパースします。 | |
tmpl, err := template.New("titleTest").Funcs(funcMap).Parse(templateText) | |
if err != nil { | |
log.Fatalf("parsing: %s", err) | |
} | |
// 出力を確認するため、テンプレートを実行します。 | |
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