-
Notifications
You must be signed in to change notification settings - Fork 0
/
Template_PrintPerson.go
67 lines (57 loc) · 1.12 KB
/
Template_PrintPerson.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
57
58
59
60
61
62
63
64
65
66
67
/*
Template_PrintPerson
本程序使用template渲染html来输出person结构
*/
package main
import (
"fmt"
"html/template"
"os"
)
type Person struct {
Name string
Age int
Emails []string
Jobs []*Job
}
type Job struct {
Employer string
Role string
}
const template_code = `
<div>
<div>The name is {{.Name}}</div>
<div>The age is {{.Age}}</div>
<div>The emails are:</div>
{{range .Emails}}
<div>The emails are: {{.}}</div>
{{end}}
<div>The jobs are:</div>
{{with .Jobs}}
{{range .}}
<div>The employer is: {{.Employer}}, the role is {{.Role}}</div>
{{end}}
{{end}}
</div>
`
func main() {
job1 := Job{Employer: "Monash", Role: "Honorary"}
job2 := Job{Employer: "Box Hill", Role: "Head of HE"}
person := Person{
Name: "Jan",
Age: 50,
Emails: []string{"[email protected]", "[email protected]"},
Jobs: []*Job{&job1, &job2},
}
t := template.New("Person template")
t, err := t.Parse(template_code)
checkError(err)
err = t.Execute(os.Stdout, person)
checkError(err)
}
func checkError(err error) {
if err != nil {
fmt.Println("Fatal error ", err.Error())
os.Exit(1)
}
}