File tree 3 files changed +51
-44
lines changed
3 files changed +51
-44
lines changed Load Diff This file was deleted.
Original file line number Diff line number Diff line change @@ -52,6 +52,11 @@ func (s *Server) Run() {
52
52
r .Handle ("/note" , saveNoteHandler (s .DB )).Methods ("POST" )
53
53
r .Handle ("/note/{id}" , readNoteHandler (s .DB )).Methods ("GET" )
54
54
55
+ // Initialize templates (durty solution)
56
+ if err := initTemplates (); err != nil {
57
+ log .Fatal (err )
58
+ }
59
+
55
60
log .Printf ("Starting tornote server on %s" , s .Host )
56
61
log .Fatal (http .ListenAndServe (s .Host , r ))
57
62
}
Original file line number Diff line number Diff line change @@ -18,14 +18,59 @@ package tornote
18
18
19
19
import (
20
20
"errors"
21
+ "html/template"
22
+ "log"
21
23
"net/http"
22
24
)
23
25
26
+ var templates map [string ]* template.Template
27
+
28
+ // Load and compile templates files from bindata.
29
+ func initTemplates () error {
30
+ if templates == nil {
31
+ templates = make (map [string ]* template.Template )
32
+ }
33
+
34
+ layout , err := Asset ("templates/layout/base.html" )
35
+ if err != nil {
36
+ log .Fatal (err )
37
+ }
38
+
39
+ pages , err := AssetDir ("templates" )
40
+ if err != nil {
41
+ log .Fatal (err )
42
+ }
43
+
44
+ for _ , file := range pages {
45
+ // Skip layout dir
46
+ if file == "layout" {
47
+ continue
48
+ }
49
+ // Get template data from bindata
50
+ templateData , err := Asset ("templates/" + file )
51
+ if err != nil {
52
+ return err
53
+ }
54
+ // Compile layout
55
+ target , err := template .New (file ).Parse (string (layout ))
56
+ if err != nil {
57
+ return err
58
+ }
59
+ // Compile target template
60
+ templates [file ], err = target .Parse (string (templateData ))
61
+ if err != nil {
62
+ return err
63
+ }
64
+ }
65
+
66
+ return nil
67
+ }
68
+
24
69
// Wrapper around template.ExecuteTemplate method.
25
70
func renderTemplate (w http.ResponseWriter , name string , data interface {}) error {
26
71
tmpl , ok := templates [name ]
27
72
if ! ok {
28
- return errors .New ("This template doesn't exist. " )
73
+ return errors .New ("This template doesn't exist" )
29
74
}
30
75
31
76
w .Header ().Set ("Content-Type" , "text/html; charset=utf-8" )
You can’t perform that action at this time.
0 commit comments