forked from boombuler/knowledgedb
/
templates.go
91 lines (78 loc) · 1.94 KB
/
templates.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 main
import (
"github.com/boombuler/knowledgedb/config"
"github.com/boombuler/knowledgedb/log"
"github.com/boombuler/knowledgedb/markdown"
"html/template"
"io/ioutil"
"net/http"
"os"
"path"
"time"
)
var templates map[string]*template.Template
var mdContent map[string]string = map[string]string{
"help": "help.md",
}
func initTemplates() {
templateDir := path.Join(config.ApplicationDir, "templates")
html := []string{
"markdown", // needed for "renderMarkdown"
"edit_document",
"view_document",
"create_document",
"search_result",
"index",
"tag",
"licenses",
}
myFuncs := template.FuncMap{
"fmtDateTime": func(t time.Time) string {
return t.Format("02.01.2006 15:04:05")
},
"markdown": func(text string) template.HTML {
return markdown.ToHtml(text)
},
}
templates = make(map[string]*template.Template)
addTemplate := func(name string, files ...string) {
fList := make([]string, len(files))
for i, f := range files {
fList[i] = path.Join(templateDir, f)
}
templates[name] = template.Must(template.New(name).Funcs(myFuncs).ParseFiles(fList...))
}
for _, t := range html {
addTemplate(t, "base.html", t+".html")
}
for k, v := range mdContent {
f, err := os.Open(path.Join(templateDir, v))
if err != nil {
log.Fatal(err)
}
defer f.Close()
content, err := ioutil.ReadAll(f)
if err != nil {
log.Fatal(err)
}
mdContent[k] = string(content)
}
}
func renderTemplate(w http.ResponseWriter, tmpl string, p interface{}) {
tmplInstance, ok := templates[tmpl]
if !ok {
log.Fatal("Invalid Template:", tmpl)
}
err := tmplInstance.ExecuteTemplate(w, "base.html", p)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
log.Fatal("Template Error", err)
}
}
func renderMarkdown(w http.ResponseWriter, contentName string) {
md, ok := mdContent[contentName]
if !ok {
log.Fatal("Invalid Pagename:", contentName)
}
renderTemplate(w, "markdown", md)
}