Skip to content

Commit 8768ab6

Browse files
committed
Add txttmpl/missingkey.go
1 parent a4ce308 commit 8768ab6

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

examples/basic/templates/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,4 @@
4343
| txttmpl/parsefuncs/parsefiles.go | templates_parsefuncs_parsefiles | template.ParseFiles() のサンプルです. |
4444
| txttmpl/parsefuncs/parseglob.go | templates_parsefuncs_parseglob | template.ParseGlob() のサンプルです. |
4545
| htmltmpl/escape.go | templates_html_tmpl_escape | html/template にて適用されるHTMLエスケープについてのサンプルです. |
46+
| txttmpl/missingkey.go | templates_text_tmpl_missingkey | text/template の missingkey=zero オプション指定時のサンプルです。 |

examples/basic/templates/txttmpl/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ func (r *register) Regist(m mapping.ExampleMapping) {
5151
m["templates_text_tmpl_with"] = With
5252
m["templates_text_tmpl_define"] = Define
5353
m["templates_text_tmpl_funcmap"] = FuncMap
54+
m["templates_text_tmpl_missingkey"] = MissingKey
5455

5556
parsefuncs.NewRegister().Regist(m)
5657
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package txttmpl
2+
3+
import (
4+
"fmt"
5+
"os"
6+
"text/template"
7+
)
8+
9+
// MissingKey -- text/template の missingkey=zero オプション指定時のサンプルです。
10+
//
11+
// Template.Option("missingkey=zero")の設定を行い、テンプレートに対して map[string]any をデータとして指定した場合
12+
// キーに対応する値が nil の場合、"<no value>" と表示されることに注意。(マップの値の方の方がanyのため)
13+
//
14+
// 当然、any以外の場合はその型のゼロ値となる。
15+
//
16+
// # REFERENCES
17+
// - https://pkg.go.dev/text/template@latest
18+
func MissingKey() error {
19+
const (
20+
TEXT = `{{.Value}} world`
21+
)
22+
var (
23+
mAny = map[string]any{"Value": "hello"}
24+
mStr = map[string]string{"Value": "hello"}
25+
mInt = map[string]int{"Value": 100}
26+
27+
t = template.Must(template.New("MissingKey").Option("missingkey=zero").Parse(TEXT))
28+
fn = func(message string) {
29+
fmt.Printf("[%s] -----------------------\n", message)
30+
t.Execute(os.Stdout, mAny)
31+
fmt.Println("")
32+
t.Execute(os.Stdout, mStr)
33+
fmt.Println("")
34+
t.Execute(os.Stdout, mInt)
35+
fmt.Println("")
36+
}
37+
)
38+
fn("キーあり")
39+
40+
delete(mAny, "Value")
41+
delete(mStr, "Value")
42+
delete(mInt, "Value")
43+
44+
fn("キーなし")
45+
46+
return nil
47+
48+
/*
49+
$ task
50+
task: [run] ./try-golang -onetime
51+
52+
ENTER EXAMPLE NAME: templates_text_tmpl_missingkey
53+
54+
[Name] "templates_text_tmpl_missingkey"
55+
[キーあり] -----------------------
56+
hello world
57+
hello world
58+
100 world
59+
[キーなし] -----------------------
60+
<no value> world
61+
world
62+
0 world
63+
64+
[Elapsed] 79.082µs
65+
*/
66+
}

0 commit comments

Comments
 (0)