-
Notifications
You must be signed in to change notification settings - Fork 8
/
template.go
91 lines (85 loc) · 2.22 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 docsite
import (
"context"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
"github.com/pkg/errors"
"github.com/sourcegraph/docsite/markdown"
)
const (
rootTemplateName = "root"
documentTemplateName = "document"
searchTemplateName = "search"
)
func (s *Site) getTemplate(templatesFS http.FileSystem, name string, extraFuncs template.FuncMap) (*template.Template, error) {
readFile := func(fs http.FileSystem, path string) ([]byte, error) {
f, err := fs.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return data, nil
}
tmpl := template.New(rootTemplateName)
tmpl.Funcs(template.FuncMap{
"asset": func(path string) string {
return s.AssetsBase.ResolveReference(&url.URL{Path: path}).String()
},
"contentFileExists": func(version, path string) bool {
fs, err := s.Content.OpenVersion(context.Background(), version)
if err != nil {
return false
}
f, err := fs.Open(path)
// Treat all errors as "not-exists".
if f != nil {
f.Close()
}
return err == nil
},
"renderMarkdownContentFile": func(version, path string) (template.HTML, error) {
fs, err := s.Content.OpenVersion(context.Background(), version)
if err != nil {
return "", err
}
data, err := readFile(fs, path)
if err != nil {
return "", err
}
doc, err := markdown.Run(context.Background(), data, s.markdownOptions(path, version))
if err != nil {
return "", err
}
return template.HTML(doc.HTML), nil
},
"subtract": func(a, b int) int { return a - b },
"replace": strings.Replace,
"trimPrefix": strings.TrimPrefix,
})
tmpl.Funcs(extraFuncs)
// Read root and named template files.
names := []string{rootTemplateName, name}
for _, name := range names {
path := "/" + name + ".html"
data, err := ReadFile(templatesFS, path)
if name == rootTemplateName && os.IsNotExist(err) {
continue
}
if err != nil {
return nil, errors.WithMessage(err, fmt.Sprintf("read template %s", path))
}
if _, err := tmpl.Parse(string(data)); err != nil {
return nil, errors.WithMessage(err, fmt.Sprintf("parse template %s", path))
}
}
return tmpl, nil
}