-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhtml.go
50 lines (42 loc) · 938 Bytes
/
html.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
package main
import (
"bytes"
"html/template"
"io/fs"
"os"
"path/filepath"
)
func parseTemplates(dir string) (*template.Template, error) {
tmpl := template.New("").Funcs(template.FuncMap{
"md2html": func(s string) template.HTML {
b := new(bytes.Buffer)
err := md.Convert([]byte(s), b)
if err != nil {
return template.HTML("<p>failed to convert to html</p>")
}
return template.HTML(b.Bytes())
},
})
err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if filepath.Ext(d.Name()) == ".html" {
_, err = tmpl.ParseFiles(path)
}
return err
})
if err != nil {
return nil, err
}
return tmpl, nil
}
func toHTML[T any](tmpl *template.Template, layout, out string, data T) error {
outFile, err := os.Create(out)
if err != nil {
return err
}
defer outFile.Close()
err = tmpl.ExecuteTemplate(outFile, layout, data)
if err != nil {
return err
}
return nil
}