Repository navigation
Expand file tree
/
Copy pathvingo.go
More file actions
103 lines (86 loc) · 1.92 KB
/
Copy pathvingo.go
File metadata and controls
103 lines (86 loc) · 1.92 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package vingo
import (
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// AutoEscape: template motoru değişken çıktılarında varsayılan olarak HTML kaçışını (escaping) aktifleştirir.
// Bunu false yaparak global olarak otomatik kaçışı kapatabilirsiniz (önerilmez).
var AutoEscape = true
type Template struct {
Filepath string
Nodes []Node
ModTime time.Time
}
var (
// cache: filepath -> compiled template
tplCache = map[string]*Template{}
cacheMutex sync.RWMutex
)
// Render: template dosyasını oku, compile et (gerekirse cache'den), ve işle
func Render(file string, data map[string]interface{}) (string, error) {
abs, err := filepath.Abs(file)
if err != nil {
abs = file
}
tpl, err := getOrCompile(abs)
if err != nil {
return "", err
}
// Evaluate
out := &strings.Builder{}
for _, n := range tpl.Nodes {
out.WriteString(n.Eval(data))
}
return out.String(), nil
}
// getOrCompile: cache kontrolü + compile
func getOrCompile(path string) (*Template, error) {
stat, err := os.Stat(path)
if err != nil {
return nil, err
}
mod := stat.ModTime()
cacheMutex.RLock()
tpl, exists := tplCache[path]
cacheMutex.RUnlock()
if exists && tpl.ModTime.Equal(mod) {
return tpl, nil
}
// compile
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
content := string(b)
tokens := tokenize(content)
nodes, err := compileTokens(tokens)
if err != nil {
return nil, err
}
newTpl := &Template{
Filepath: path,
Nodes: nodes,
ModTime: mod,
}
cacheMutex.Lock()
tplCache[path] = newTpl
cacheMutex.Unlock()
return newTpl, nil
}
func evalNodes(nodes []Node, data map[string]interface{}) string {
out := &strings.Builder{}
for _, n := range nodes {
out.WriteString(n.Eval(data))
}
return out.String()
}
func shallowCopyMap(m map[string]interface{}) map[string]interface{} {
n := make(map[string]interface{}, len(m)+4)
for k, v := range m {
n[k] = v
}
return n
}