/
views_default.go
117 lines (93 loc) · 2.38 KB
/
views_default.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package attache
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
"html/template"
"github.com/Masterminds/sprig"
viewDriver "github.com/attache/attache/drivers/view"
)
func init() {
driver := attacheViews{}
viewDriver.DriverRegister("", driver)
viewDriver.DriverRegister("attache", driver)
}
type attacheViews struct{}
func (a attacheViews) Init(root string) (*viewDriver.Cache, error) {
cache := new(viewDriver.Cache)
if err := a.load(cache, root, "", nil); err != nil {
return nil, err
}
return cache, nil
}
type viewLayout struct {
File, Body string
}
var viewParseErrRx = regexp.MustCompile("^template: (?:[^:]*):([0-9]+): (.*)")
func viewParseError(currentFile string, e error) error {
result := viewParseErrRx.FindStringSubmatch(e.Error())
if result != nil {
return fmt.Errorf("parse %s: line %s: %s", currentFile, result[1], result[2])
}
return fmt.Errorf("parse %s: %s", currentFile, e)
}
func (a attacheViews) load(c *viewDriver.Cache, path, prefix string, layouts []viewLayout) error {
const layoutFileName = "layout.go.html"
stats, err := ioutil.ReadDir(path)
if err != nil {
return err
}
layoutPath := filepath.Join(path, layoutFileName)
layout, err := ioutil.ReadFile(layoutPath)
if err != nil && !os.IsNotExist(err) {
return err
}
if layout != nil {
layouts = append(layouts, viewLayout{
File: layoutPath,
Body: string(layout),
})
}
var subdirs []string
for _, file := range stats {
fpath := filepath.Join(path, file.Name())
if file.IsDir() {
subdirs = append(subdirs, fpath)
continue
}
if file.Name() == layoutFileName {
continue
}
tpl := template.New("").Funcs(sprig.FuncMap())
for _, l := range layouts {
if _, err := tpl.Parse(l.Body); err != nil {
return viewParseError(l.File, err)
}
}
if _, err := tpl.ParseFiles(fpath); err != nil {
return viewParseError(fpath, err)
}
var tplName string
if prefix == "" {
tplName = strings.TrimSuffix(file.Name(), ".go.html")
} else {
tplName = fmt.Sprintf("%s.%s", prefix, strings.TrimSuffix(file.Name(), ".go.html"))
}
c.Put(tplName, tpl)
}
for _, dir := range subdirs {
var newPrefix string
if prefix == "" {
newPrefix = filepath.Base(dir)
} else {
newPrefix = fmt.Sprintf("%s.%s", prefix, filepath.Base(dir))
}
if err := a.load(c, dir, newPrefix, layouts); err != nil {
return err
}
}
return nil
}