-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgentemplate.go
77 lines (72 loc) · 1.2 KB
/
gentemplate.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
68
69
70
71
72
73
74
75
76
77
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"os"
)
func main() {
genFromTemplate()
}
func genFromTemplate() {
funcs := template.FuncMap{
"AddFloats": func(x, y float64) float64 {
return x + y
},
"AddInts": func(x, y int) int {
return x + y
},
}
tmpl, err := template.New("template.html").Funcs(funcs).ParseFiles("template.html")
if err != nil {
log.Fatalln(err)
}
type Cart struct {
Item string
Amount float64
}
d := map[string]any{
"Items": []Cart{
{
Item: "Bread",
Amount: 24,
},
{
Item: "Rice",
Amount: 56.7,
},
{
Item: "Clothes",
Amount: 150.45,
},
{
Item: "Water",
Amount: 100,
},
{
Item: "Gas",
Amount: 100.00,
},
},
"Title": "Inventory list",
}
data, err := json.Marshal(d)
if err != nil {
log.Fatalln(err)
}
f, err := os.Create("output.html")
if err != nil {
log.Fatalln("Output file create err:", err)
}
fmt.Println(string(data))
convertData := map[string]interface{}{}
err = json.Unmarshal(data, &convertData)
if err != nil {
log.Fatalln(err)
}
err = tmpl.Execute(f, convertData)
if err != nil {
log.Fatalln("template execute failure:", err)
}
}