-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.go
More file actions
203 lines (173 loc) · 6.69 KB
/
template.go
File metadata and controls
203 lines (173 loc) · 6.69 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package templar
import (
"bytes"
"errors"
"fmt"
"log"
"log/slog"
"path/filepath"
ttmpl "text/template"
gotl "github.com/panyam/goutils/template"
)
// TemplateNotFound is returned when a template could not be found by a loader.
var TemplateNotFound = errors.New("template not found")
// Template is the basic unit of rendering that manages content and dependencies.
type Template struct {
// Name is an identifier for this template.
Name string
// RawSource contains the original, unprocessed template content.
RawSource []byte
// ParsedSource contains the template content after preprocessing.
ParsedSource string
// CleanedSource contains the template after all the includes are removed but before any preprocessing is done
cleanedSource string
// Path is the file path for this template if it was loaded from a file.
Path string
// Status indicates whether the template has been loaded and parsed.
Status int
// AsHtml determines whether the content should be treated as HTML (with escaping)
// or as plain text.
AsHtml bool
// includes contains other templates that this template depends on.
includes []*Template
// Error contains any error encountered during template processing.
Error error
// Metadata stores extracted information from the template (e.g., FrontMatter).
Metadata map[string]any
// Namespace is set when this template was included via namespace directive.
// When set, all template definitions and references will be prefixed with this namespace.
Namespace string
// NamespaceEntryPoints specifies which templates to include when namespacing.
// If empty, all templates are included. If set, only these templates and their
// transitive dependencies are included (tree-shaking).
NamespaceEntryPoints []string
// Extensions records extend directives to be processed after all templates are parsed.
// Each extension creates a new template by copying a source and rewiring references.
Extensions []Extension
}
// Extension represents an extend directive that creates a new template by copying
// a source template and rewiring specific template references.
//
// Syntax: {{# extend "SourceTemplate" "DestTemplate" "block1" "override1" "block2" "override2" ... #}}
//
// This creates DestTemplate as a copy of SourceTemplate, but with:
// - {{ template "block1" . }} replaced with {{ template "override1" . }}
// - {{ template "block2" . }} replaced with {{ template "override2" . }}
type Extension struct {
// SourceTemplate is the template to copy from (e.g., "Base:layout")
SourceTemplate string
// DestTemplate is the name for the new template (e.g., "Page:layout")
DestTemplate string
// Rewrites maps block names to their replacements.
// Key is the original reference, value is the replacement.
Rewrites map[string]string
}
// Returns the cleaned source of this template wihtout all the includes removed (but before they are preprocessed)
func (t *Template) CleanedSource() (string, error) {
if t.cleanedSource == "" {
fm2 := ttmpl.FuncMap{
"dict": gotl.ValuesToDict,
"include": func(glob string) (string, error) {
return fmt.Sprintf("{{/* Removed Include: '%s' */}}", glob), nil
},
}
buff2 := bytes.NewBufferString("")
templ2, err := ttmpl.New("").Funcs(fm2).Delims("{{#", "#}}").Parse(string(t.RawSource))
if err != nil {
slog.Error("error removing includes in template: ", "path", t.Path, "error", err)
return t.cleanedSource, panicOrError(err)
}
if err := templ2.Execute(buff2, nil); err != nil {
slog.Error("error removing includes in template: ", "path", t.Path, "error", err)
t.Error = err
return t.cleanedSource, panicOrError(err)
} else {
t.cleanedSource = buff2.String()
}
}
return t.cleanedSource, nil
}
// AddDependency adds another template as a dependency of this template.
// It returns false if the dependency would create a cycle, true otherwise.
func (t *Template) AddDependency(another *Template) bool {
if t.Path != "" {
for _, child := range t.includes {
// TODO - check full cycles
if child.Path == another.Path {
return false
}
}
t.includes = append(t.includes, another)
}
return true
}
// Dependencies returns all templates that this template directly depends on.
func (t *Template) Dependencies() []*Template {
return t.includes
}
// TemplateLoader defines an interface for loading template content by name or pattern.
type TemplateLoader interface {
// Load attempts to load templates matching the given pattern.
// If cwd is not empty, it's used as the base directory for relative paths.
// Returns matching templates or an error if no templates were found.
Load(pattern string, cwd string) (template []*Template, err error)
}
func (root *Template) WalkTemplate(loader TemplateLoader, handler func(template *Template) error) (err error) {
// An Inorder walk of of a template. Unlike WalkTemplate which applies a PostOrder traversal (first collects all
// includes, processes them and then the root template), here we will process an included template as soon as it is
// encountered.
cwd := root.Path
if cwd != "" {
cwd = filepath.Dir(cwd)
}
// log.Println("Coming from : ", root.Name)
// defer log.Println("Finished with: ", root.Name, root.Path)
var includes []string
fm := ttmpl.FuncMap{
"include": func(glob string) string {
log.Println("Coming to: ", glob)
// TODO - avoid duplicates
includes = append(includes, glob)
return fmt.Sprintf("{{/* Including: '%s' */}}", glob)
},
}
// First parse the macro template
templ, err := ttmpl.New("").Funcs(fm).Delims("{{#", "#}}").Parse(string(root.RawSource))
if err != nil {
slog.Error("error template: ", "path", root.Path, "error", err)
return panicOrError(err)
}
// New execute it so that all includes are evaluated
buff := bytes.NewBufferString("")
if err := templ.Execute(buff, nil); err != nil {
slog.Error("error preprocessing template: ", "path", root.Path, "error", err)
root.Error = err
return panicOrError(err)
} else {
root.ParsedSource = buff.String()
}
// Resolve the includes - for now non-wildcards are only allowed
for _, included := range includes {
children, err := loader.Load(included, cwd)
if err != nil {
slog.Error("error loading include: ", "included", included, "error", err)
return panicOrError(err)
}
for _, child := range children {
if child.Path != "" {
if !root.AddDependency(child) {
slog.Error(fmt.Sprintf("found cyclical dependency: %s -> %s", child.Path, root.Path), "from", child.Path, "to", root.Path)
continue
}
}
err = child.WalkTemplate(loader, handler)
if err != nil {
slog.Error("error walking", "included", included, "error", err)
root.Error = err
return panicOrError(err)
}
}
}
// No handle this template
return handler(root)
}