This repository has been archived by the owner on Dec 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtemplate.go
91 lines (72 loc) · 1.95 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
79
80
81
82
83
84
85
86
87
88
89
90
91
package grender
import (
"bufio"
"html/template"
"os"
"path/filepath"
"regexp"
)
var extendsRegex *regexp.Regexp
func init() {
var err error
extendsRegex, err = regexp.Compile(`\{\{\/\* *?extends +?"(.+?)" *?\*\/\}\}`)
if err != nil {
panic(err)
}
}
func (r *Grender) compileTemplatesFromDir() {
if r.Options.TemplatesGlob == "" {
return
}
// replace existing templates.
// NOTE: this is unsafe, but Debug should really not be true in production environments.
templateSet := make(map[string]*template.Template)
files, err := filepath.Glob(r.Options.TemplatesGlob)
if err != nil {
panic(err)
}
baseTmpl := template.New("").Funcs(r.Options.Funcs)
// parse partials (glob)
if r.Options.PartialsGlob != "" {
baseTmpl = template.Must(baseTmpl.ParseGlob(r.Options.PartialsGlob))
}
for _, templateFile := range files {
fileName := filepath.Base(templateFile)
layout := getLayoutForTemplate(templateFile)
// set template name
name := fileName
if layout != "" {
name = filepath.Base(layout)
}
tmpl := template.Must(baseTmpl.Clone())
tmpl = tmpl.New(name)
// parse master template
if layout != "" {
layoutFile := filepath.Join(filepath.Dir(templateFile), layout)
tmpl = template.Must(tmpl.ParseFiles(layoutFile))
}
// parse child template
tmpl = template.Must(tmpl.ParseFiles(templateFile))
templateSet[fileName] = tmpl
}
r.Templates.set = templateSet
}
// Lookup returns the compiled template by its filename or nil if there is no such template
func (t *templates) Lookup(name string) *template.Template {
return t.set[name]
}
// getLayoutForTemplate scans the first line of the template file for the extends keyword
func getLayoutForTemplate(filename string) string {
file, err := os.Open(filename)
if err != nil {
panic(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Scan()
b := scanner.Bytes()
if l := extendsRegex.FindSubmatch(b); l != nil {
return string(l[1])
}
return ""
}