-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
55 lines (45 loc) · 1.19 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
// /template.go
// Template manages HTML template parsing and rendering
package stardust
import (
"html/template"
"net/http"
"path/filepath"
"sync"
)
type Template struct {
dir string // template directory
templates *template.Template // parsed templates cache
mutex sync.RWMutex // ensures thread-safe template operations
}
// NewTemplate creates a new Template instance for the specified directory
func NewTemplate(dir string) *Template {
return &Template{
dir: dir,
}
}
// Load parses all HTML templates in the template directory
func (t *Template) Load() error {
t.mutex.Lock()
defer t.mutex.Unlock()
// Find all template files
pattern := filepath.Join(t.dir, "*.html")
tmpl, err := template.ParseGlob(pattern)
if err != nil {
return err
}
t.templates = tmpl
return nil
}
// Render executes a template with the given name and data
func (t *Template) Render(w http.ResponseWriter, name string, data interface{}) error {
t.mutex.RLock()
defer t.mutex.RUnlock()
if t.templates == nil {
if err := t.Load(); err != nil {
return err
}
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
return t.templates.ExecuteTemplate(w, name, data)
}