-
Notifications
You must be signed in to change notification settings - Fork 98
/
template.go
78 lines (72 loc) · 1.84 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"fmt"
"io"
"time"
"github.com/CloudyKit/jet/v6"
"github.com/labstack/echo/v4"
"github.com/quiq/registry-ui/registry"
"github.com/spf13/viper"
)
// Template Jet template.
type Template struct {
View *jet.Set
}
// Render render template.
func (r *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
t, err := r.View.GetTemplate(name)
if err != nil {
panic(fmt.Errorf("fatal error template file: %s", err))
}
vars, ok := data.(jet.VarMap)
if !ok {
vars = jet.VarMap{}
}
err = t.Execute(w, vars, nil)
if err != nil {
panic(fmt.Errorf("error rendering template %s: %s", name, err))
}
return nil
}
// setupRenderer template engine init.
func setupRenderer(basePath string) *Template {
var opts []jet.Option
if viper.GetBool("debug.templates") {
opts = append(opts, jet.InDevelopmentMode())
}
view := jet.NewSet(jet.NewOSFileSystemLoader("templates"), opts...)
view.AddGlobal("version", version)
view.AddGlobal("basePath", basePath)
view.AddGlobal("registryHost", viper.GetString("registry.hostname"))
view.AddGlobal("pretty_size", func(val interface{}) string {
var s float64
switch i := val.(type) {
case int64:
s = float64(i)
case float64:
s = i
default:
fmt.Printf("Unhandled type when calling pretty_size(): %T\n", i)
}
return registry.PrettySize(s)
})
view.AddGlobal("pretty_time", func(val interface{}) string {
var t time.Time
switch i := val.(type) {
case string:
var err error
t, err = time.Parse("2006-01-02T15:04:05Z", i)
if err != nil {
// mysql case
t, _ = time.Parse("2006-01-02 15:04:05", i)
}
default:
t = i.(time.Time)
}
return t.In(time.Local).Format("2006-01-02 15:04:05 MST")
})
view.AddGlobal("sort_map_keys", func(m interface{}) []string {
return registry.SortedMapKeys(m)
})
return &Template{View: view}
}