Skip to content

Commit b8b9bb0

Browse files
authored
Merge pull request #501 from devlights/add-txt-template-funcmap-example
2 parents 370712a + a7041f4 commit b8b9bb0

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

examples/basic/templates/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,4 @@
3838
|txttmpl/pipe.go|templates\_text\_tmpl\_pipe|text/template の テンプレート仕様 における pipe のサンプルです.|
3939
|txttmpl/with.go|templates\_text\_tmpl\_with|text/template の テンプレート仕様 における with のサンプルです.|
4040
|txttmpl/with.go|templates\_text\_tmpl\_define|text/template の テンプレート仕様 における define (独自テンプレートの定義) のサンプルです.|
41+
|txttmpl/with.go|templates\_text\_tmpl\_funcmap|text/template の テンプレート仕様 における funcmap (独自関数の定義) のサンプルです.|

examples/basic/templates/txttmpl/examples.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,5 @@ func (r *register) Regist(m mapping.ExampleMapping) {
4747
m["templates_text_tmpl_pipe"] = Pipe
4848
m["templates_text_tmpl_with"] = With
4949
m["templates_text_tmpl_define"] = Define
50+
m["templates_text_tmpl_funcmap"] = FuncMap
5051
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package txttmpl
2+
3+
import (
4+
"bytes"
5+
"strings"
6+
"text/template"
7+
8+
"github.com/devlights/gomy/output"
9+
)
10+
11+
// FuncMap -- text/template の テンプレート仕様 における FuncMap (独自関数の登録) のサンプルです.
12+
//
13+
// # REFERENCES
14+
// - https://pkg.go.dev/text/template@latest
15+
func FuncMap() error {
16+
var (
17+
tmpls = []string{
18+
`{{ upper . }} {{ upper (fn .) }}`,
19+
}
20+
fn = func(v interface{}) string {
21+
s, ok := v.(string)
22+
if !ok {
23+
return ""
24+
}
25+
26+
var (
27+
result = make([]byte, len(s))
28+
lastIdx = len(s) - 1
29+
)
30+
31+
for i, j := lastIdx, 0; i >= 0; i, j = i-1, j+1 {
32+
result[j] = s[i]
33+
}
34+
35+
return string(result)
36+
}
37+
funcs = template.FuncMap{
38+
"fn": fn,
39+
"upper": strings.ToUpper,
40+
}
41+
)
42+
43+
for _, t := range tmpls {
44+
var (
45+
tmpl *template.Template
46+
buf bytes.Buffer
47+
err error
48+
)
49+
50+
output.Stdoutl("[template]", t)
51+
52+
// 独自関数を利用する場合は Parse の呼び出しの前に Funcs を呼び出す必要がある
53+
tmpl, err = template.New("FuncMap").Funcs(funcs).Parse(t)
54+
if err != nil {
55+
return err
56+
}
57+
58+
err = tmpl.Execute(&buf, "helloworld")
59+
if err != nil {
60+
return err
61+
}
62+
63+
output.Stdoutf("[tmpl]", "%s\n", buf.String())
64+
output.StdoutHr()
65+
}
66+
67+
return nil
68+
}

0 commit comments

Comments
 (0)