Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/basic/templates/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,4 @@
| txttmpl/parsefuncs/parsefiles.go | templates_parsefuncs_parsefiles | template.ParseFiles() のサンプルです. |
| txttmpl/parsefuncs/parseglob.go | templates_parsefuncs_parseglob | template.ParseGlob() のサンプルです. |
| htmltmpl/escape.go | templates_html_tmpl_escape | html/template にて適用されるHTMLエスケープについてのサンプルです. |
| txttmpl/missingkey.go | templates_text_tmpl_missingkey | text/template の missingkey=zero オプション指定時のサンプルです。 |
1 change: 1 addition & 0 deletions examples/basic/templates/txttmpl/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ func (r *register) Regist(m mapping.ExampleMapping) {
m["templates_text_tmpl_with"] = With
m["templates_text_tmpl_define"] = Define
m["templates_text_tmpl_funcmap"] = FuncMap
m["templates_text_tmpl_missingkey"] = MissingKey

parsefuncs.NewRegister().Regist(m)
}
66 changes: 66 additions & 0 deletions examples/basic/templates/txttmpl/missingkey.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package txttmpl

import (
"fmt"
"os"
"text/template"
)

// MissingKey -- text/template の missingkey=zero オプション指定時のサンプルです。
//
// Template.Option("missingkey=zero")の設定を行い、テンプレートに対して map[string]any をデータとして指定した場合
// キーに対応する値が nil の場合、"<no value>" と表示されることに注意。(マップの値の方の方がanyのため)
//
// 当然、any以外の場合はその型のゼロ値となる。
//
// # REFERENCES
// - https://pkg.go.dev/text/template@latest
func MissingKey() error {
const (
TEXT = `{{.Value}} world`
)
var (
mAny = map[string]any{"Value": "hello"}
mStr = map[string]string{"Value": "hello"}
mInt = map[string]int{"Value": 100}

t = template.Must(template.New("MissingKey").Option("missingkey=zero").Parse(TEXT))
fn = func(message string) {
fmt.Printf("[%s] -----------------------\n", message)
t.Execute(os.Stdout, mAny)
fmt.Println("")
t.Execute(os.Stdout, mStr)
fmt.Println("")
t.Execute(os.Stdout, mInt)
fmt.Println("")
}
)
fn("キーあり")

delete(mAny, "Value")
delete(mStr, "Value")
delete(mInt, "Value")

fn("キーなし")

return nil

/*
$ task
task: [run] ./try-golang -onetime

ENTER EXAMPLE NAME: templates_text_tmpl_missingkey

[Name] "templates_text_tmpl_missingkey"
[キーあり] -----------------------
hello world
hello world
100 world
[キーなし] -----------------------
<no value> world
world
0 world

[Elapsed] 79.082µs
*/
}
Loading