-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.go
More file actions
82 lines (74 loc) · 2.13 KB
/
Copy pathtemplate.go
File metadata and controls
82 lines (74 loc) · 2.13 KB
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
package main
import (
"fmt"
"html/template"
"reflect"
"sync"
)
var (
compiledTemplates map[string]*template.Template
compiledTemplatesOnce sync.Once
compiledTemplatesErr error
)
var templateFiles = map[string]string{
"allPosts": "templates/allPosts.html",
"blogPost": "templates/blogPost.html",
"books": "templates/books.html",
"cheatsheets": "templates/cheatsheets.html",
"error": "templates/error.html",
"filters": "templates/filters.html",
"home": "templates/home.html",
"interviews": "templates/interviews.html",
"pictures": "templates/pictures.html",
"projects": "templates/projects.html",
"running": "templates/running.html",
"simpleMarkdown": "templates/simpleMarkdown.html",
}
// initializeTemplates parses every page template before the HTTP server accepts
// requests. The resulting templates are safe for concurrent execution.
func initializeTemplates() error {
compiledTemplatesOnce.Do(func() {
compiledTemplates = make(map[string]*template.Template, len(templateFiles))
for name, pageFile := range templateFiles {
t, err := template.New("base.html").Funcs(funcMap).ParseFiles("templates/base.html", pageFile)
if err != nil {
compiledTemplatesErr = fmt.Errorf("parse %s template: %w", name, err)
return
}
compiledTemplates[name] = t
}
})
return compiledTemplatesErr
}
func executeTemplate(wr templateWriter, name string, data interface{}) error {
if err := initializeTemplates(); err != nil {
return err
}
t, ok := compiledTemplates[name]
if !ok {
return fmt.Errorf("unknown template %q", name)
}
return t.Execute(wr, data)
}
type templateWriter interface {
Write([]byte) (int, error)
}
func avail(name string, data interface{}) bool {
v := reflect.ValueOf(data)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return false
}
field := v.FieldByName(name)
if !field.IsValid() {
return false
}
// Check if the field is a string and not empty
if field.Kind() == reflect.String {
return field.String() != ""
}
// Return true if the field is not a string but is valid
return true
}