-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathtemplate.go
56 lines (46 loc) · 1.27 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package main
import (
"os"
templ "text/template"
)
// Context is used by the template
type Context struct {
People []Person
}
// Person represents, well, a person
type Person struct {
Name string //exported field since it begins with a capital letter
Senior bool
}
func main() {
// With example 1
t := templ.New("'With' Example 1")
templ.Must(t.Parse(`
With inline Variable:{{with $3 := "hello"}} {{$3}} {{end}}, with an inline variable
`))
t.Execute(os.Stdout, nil)
// With example 2
t2 := templ.New("'With' Example 2")
templ.Must(t2.Parse(`
Current Value:{{with "mom"}} {{.}} {{end}}, with the current value
`))
t2.Execute(os.Stdout, nil)
// If-Else example
tIfElse := templ.New("If Else Example")
ctx := Person{Name: "Mary", Senior: false}
tIfElse = templ.Must(
tIfElse.Parse(`
If-Else example:{{if eq $.Senior true }} Yes, {{.Name}} is a senior {{else}} No, {{.Name}} is not a senior {{end}}
`))
tIfElse.Execute(os.Stdout, ctx)
// Range example
tRange := templ.New("Range Example")
ctx2 := Context{People: []Person{Person{Name: "Mary", Senior: false}, Person{Name: "Joseph", Senior: true}}}
tRange = templ.Must(
tRange.Parse(`
Range example:
{{range $i, $x := $.People}} Name={{$x.Name}} Senior={{$x.Senior}}
{{end}}
`))
tRange.Execute(os.Stdout, ctx2)
}