-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtemplating.go
75 lines (61 loc) · 1.73 KB
/
templating.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
// A fast web framework written in Go.
//
// Author: Vincent Composieux <vincent.composieux@gmail.com>
package gofast
import (
"fmt"
"os"
"github.com/flosch/pongo2"
"github.com/sirupsen/logrus"
)
type Templating struct {
viewsDirectory string
assetsDirectory string
}
// NewTemplating creates a new templating component instance
func NewTemplating() Templating {
return Templating{}
}
// SetViewsDirectory sets templating views directory
func (t *Templating) SetViewsDirectory(name string) {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
logrus.Warn(fmt.Sprintf("Directory '%s' does not exists", name))
os.Exit(1)
}
}
t.viewsDirectory = name
}
// GetViewsDirectory returns templating views directory
func (t *Templating) GetViewsDirectory() string {
return t.viewsDirectory
}
// SetAssetsDirectory sets templating assets directory
func (t *Templating) SetAssetsDirectory(name string) {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
logrus.Warn(fmt.Sprintf("Directory '%s' does not exists", name))
os.Exit(1)
}
}
t.assetsDirectory = name
}
// GetAssetsDirectory returns templating assets directory
func (t *Templating) GetAssetsDirectory() string {
return t.assetsDirectory
}
// Render renders a template
func (t *Templating) Render(context Context, name string) {
var filename = fmt.Sprintf("%s/%s", t.GetViewsDirectory(), name)
if _, err := os.Stat(filename); err != nil {
if os.IsNotExist(err) {
logrus.Warn(fmt.Sprintf("View '%s' does not exists", filename))
os.Exit(1)
}
}
var template = pongo2.Must(pongo2.FromFile(filename))
template.ExecuteWriter(pongo2.Context{
"request": context.GetRequest(),
"response": context.GetResponse(),
}, context.GetResponse())
}