-
Notifications
You must be signed in to change notification settings - Fork 0
/
templates.go
87 lines (75 loc) · 1.59 KB
/
templates.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
79
80
81
82
83
84
85
86
87
package main
import (
"fmt"
"sort"
"github.com/akerl/go-lambda/apigw/events"
"github.com/osteele/liquid"
)
var (
engine *liquid.Engine
templateNames = []string{
"/index.html",
}
templates = map[string]*liquid.Template{}
)
func loadTemplate(name string) error {
var err error
tplName := fmt.Sprintf("%s.hbs", name)
tplFile, found := static.String(tplName)
if !found {
return fmt.Errorf("template not found: %s", tplFile)
}
templates[name], err = engine.ParseString(tplFile)
if err != nil {
return fmt.Errorf("template failed to parse (%s): %s", tplFile, err)
}
return nil
}
func loadTemplates() error {
for _, name := range templateNames {
err := loadTemplate(name)
if err != nil {
return err
}
}
return nil
}
func init() {
engine = liquid.NewEngine()
err := loadTemplates()
if err != nil {
panic(err)
}
}
func newTemplateContext(req events.Request) (map[string]interface{}, error) {
session, err := sm.Read(req)
if err != nil {
return map[string]interface{}{}, err
}
orgs := make([]string, len(session.Memberships))
idx := 0
for org := range session.Memberships {
orgs[idx] = org
idx++
}
sort.Strings(orgs)
tc := map[string]interface{}{
"request": req,
"config": config.TemplateData,
"session": session,
"orgs": orgs,
}
return tc, nil
}
func execTemplate(name string, req events.Request) (string, error) {
ctx, err := newTemplateContext(req)
if err != nil {
return "", err
}
tpl, found := templates[name]
if !found {
return "", fmt.Errorf("template does not exist: %s", name)
}
page, err := tpl.RenderString(ctx)
return page, err
}