-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
47 lines (38 loc) · 920 Bytes
/
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
package template
import (
"bytes"
"html/template"
"io"
"io/fs"
"path/filepath"
"strings"
"github.com/honmaple/forest"
)
type EmbedLoader struct {
fs fs.FS
}
func NewEmbedLoader(f fs.FS) *EmbedLoader {
return &EmbedLoader{f}
}
func (s *EmbedLoader) Get(path string) (io.Reader, error) {
buf, err := fs.ReadFile(s.fs, path)
if err != nil {
return nil, err
}
return bytes.NewReader(buf), nil
}
func (s *EmbedLoader) Abs(base, name string) string {
if filepath.IsAbs(name) || strings.HasPrefix(name, "templates/") {
return name
}
return filepath.Join("templates", name)
}
type Template struct {
templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c forest.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
func New(f fs.FS, patterns ...string) *Template {
return &Template{template.Must(template.ParseFS(f, patterns...))}
}