forked from caddyserver/caddy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
90 lines (77 loc) · 2.1 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
package markdown
import (
"bytes"
"io/ioutil"
"text/template"
"github.com/mholt/caddy/caddyhttp/httpserver"
"github.com/mholt/caddy/caddyhttp/markdown/metadata"
)
// Data represents a markdown document.
type Data struct {
httpserver.Context
Doc map[string]string
DocFlags map[string]bool
Styles []string
Scripts []string
Files []FileInfo
}
// Include "overrides" the embedded httpserver.Context's Include()
// method so that included files have access to d's fields.
// Note: using {{template 'template-name' .}} instead might be better.
func (d Data) Include(filename string) (string, error) {
return httpserver.ContextInclude(filename, d, d.Root)
}
// execTemplate executes a template given a requestPath, template, and metadata
func execTemplate(c *Config, mdata metadata.Metadata, files []FileInfo, ctx httpserver.Context) ([]byte, error) {
mdData := Data{
Context: ctx,
Doc: mdata.Variables,
DocFlags: mdata.Flags,
Styles: c.Styles,
Scripts: c.Scripts,
Files: files,
}
b := new(bytes.Buffer)
if err := c.Template.ExecuteTemplate(b, mdata.Template, mdData); err != nil {
return nil, err
}
return b.Bytes(), nil
}
// SetTemplate reads in the template with the filename provided. If the file does not exist or is not parsable, it will return an error.
func SetTemplate(t *template.Template, name, filename string) error {
// Read template
buf, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
// Update if exists
if tt := t.Lookup(name); tt != nil {
_, err = tt.Parse(string(buf))
return err
}
// Allocate new name if not
_, err = t.New(name).Parse(string(buf))
return err
}
// GetDefaultTemplate returns the default template.
func GetDefaultTemplate() *template.Template {
return template.Must(template.New("").Parse(defaultTemplate))
}
const (
defaultTemplate = `<!DOCTYPE html>
<html>
<head>
<title>{{.Doc.title}}</title>
<meta charset="utf-8">
{{- range .Styles}}
<link rel="stylesheet" href="{{.}}">
{{- end}}
{{- range .Scripts}}
<script src="{{.}}"></script>
{{- end}}
</head>
<body>
{{.Doc.body}}
</body>
</html>`
)