-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
1674 lines (1413 loc) · 43.1 KB
/
node.go
File metadata and controls
1674 lines (1413 loc) · 43.1 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package twig
import (
"bytes"
"errors"
"fmt"
"io"
"path/filepath"
"reflect"
"strconv"
"strings"
)
// Node represents a node in the template parse tree
type Node interface {
// Render renders the node to the output
Render(w io.Writer, ctx *RenderContext) error
// Type returns the node type
Type() NodeType
// Line returns the source line number
Line() int
}
// NewRootNode creates a new root node
func NewRootNode(children []Node, line int) *RootNode {
return GetRootNode(children, line)
}
// NewTextNode creates a new text node
func NewTextNode(content string, line int) *TextNode {
return GetTextNode(content, line)
}
// NewPrintNode creates a new print node
func NewPrintNode(expression Node, line int) *PrintNode {
return GetPrintNode(expression, line)
}
// NewIfNode creates a new if node
func NewIfNode(conditions []Node, bodies [][]Node, elseBranch []Node, line int) *IfNode {
return GetIfNode(conditions, bodies, elseBranch, line)
}
// NewForNode creates a new for loop node
func NewForNode(keyVar, valueVar string, sequence Node, body, elseBranch []Node, line int) *ForNode {
return GetForNode(keyVar, valueVar, sequence, body, elseBranch, line)
}
// NewBlockNode creates a new block node
func NewBlockNode(name string, body []Node, line int) *BlockNode {
return GetBlockNode(name, body, line)
}
// NewExtendsNode creates a new extends node
func NewExtendsNode(parent Node, line int) *ExtendsNode {
return GetExtendsNode(parent, line)
}
// NewIncludeNode creates a new include node
func NewIncludeNode(template Node, variables map[string]Node, ignoreMissing, only, sandboxed bool, line int) *IncludeNode {
return GetIncludeNode(template, variables, ignoreMissing, only, sandboxed, line)
}
// NewSetNode creates a new set node
func NewSetNode(name string, value Node, line int) *SetNode {
return GetSetNode(name, value, line)
}
// NewCommentNode creates a new comment node
func NewCommentNode(content string, line int) *CommentNode {
return GetCommentNode(content, line)
}
// NewMacroNode creates a new macro node
func NewMacroNode(name string, params []string, defaults map[string]Node, body []Node, line int) *MacroNode {
return GetMacroNode(name, params, defaults, body, line)
}
// NewImportNode creates a new import node
func NewImportNode(template Node, module string, line int) *ImportNode {
return GetImportNode(template, module, line)
}
// NewFromImportNode creates a new from import node
func NewFromImportNode(template Node, macros []string, aliases map[string]string, line int) *FromImportNode {
return GetFromImportNode(template, macros, aliases, line)
}
// NodeType represents the type of a node
type NodeType int
// Node types
const (
NodeRoot NodeType = iota
NodeText
NodePrint
NodeIf
NodeFor
NodeBlock
NodeExtends
NodeInclude
NodeImport
NodeMacro
NodeSet
NodeExpression
NodeComment
NodeVerbatim
NodeElement
NodeFunction
NodeSpaceless
NodeDo
NodeModuleMethod
NodeApply
NodeSandbox
)
// RootNode represents the root of a template
type RootNode struct {
children []Node
line int
}
// TextNode represents a raw text node
type TextNode struct {
content string
line int
}
// String implementation for debugging
func (n *TextNode) String() string {
// Display spaces as visible characters for easier debugging
spacesVisual := strings.ReplaceAll(n.content, " ", "·")
return fmt.Sprintf("TextNode(%q [%s], line: %d)", n.content, spacesVisual, n.line)
}
// PrintNode represents a {{ expression }} node
type PrintNode struct {
expression Node
line int
}
// IfNode represents an if block
type IfNode struct {
conditions []Node
bodies [][]Node
elseBranch []Node
line int
}
func (n *IfNode) Type() NodeType {
return NodeIf
}
func (n *IfNode) Line() int {
return n.line
}
// Release returns the IfNode to the pool
func (n *IfNode) Release() {
ReleaseIfNode(n)
}
// Render renders the if node
func (n *IfNode) Render(w io.Writer, ctx *RenderContext) error {
// Evaluate each condition until we find one that's true
for i, condition := range n.conditions {
// Log before evaluation if debug is enabled
if IsDebugEnabled() {
LogDebug("Evaluating 'if' condition #%d at line %d", i+1, n.line)
}
// Evaluate the condition
result, err := ctx.EvaluateExpression(condition)
if err != nil {
// Log error if debug is enabled
if IsDebugEnabled() {
LogError(err, "Error evaluating 'if' condition")
}
return err
}
// Log result if debug is enabled
conditionResult := ctx.toBool(result)
if IsDebugEnabled() {
LogDebug("Condition result: %v (type: %T, raw value: %v)", conditionResult, result, result)
}
// If condition is true, render the corresponding body
if conditionResult {
if IsDebugEnabled() {
LogDebug("Entering 'if' block (condition #%d is true)", i+1)
}
// Render all nodes in the body
for _, node := range n.bodies[i] {
err := node.Render(w, ctx)
if err != nil {
return err
}
}
return nil
}
}
// If no condition was true and we have an else branch, render it
if n.elseBranch != nil {
if IsDebugEnabled() {
LogDebug("Entering 'else' block (all conditions were false)")
}
for _, node := range n.elseBranch {
err := node.Render(w, ctx)
if err != nil {
return err
}
}
}
return nil
}
// ForNode represents a for loop
type ForNode struct {
keyVar string
valueVar string
sequence Node
body []Node
elseBranch []Node
line int
}
func (n *ForNode) Type() NodeType {
return NodeFor
}
func (n *ForNode) Line() int {
return n.line
}
// Release returns the ForNode to the pool
func (n *ForNode) Release() {
ReleaseForNode(n)
}
// Render renders the for loop node
func (n *ForNode) Render(w io.Writer, ctx *RenderContext) error {
// Add debug info about the sequence node
if IsDebugEnabled() {
LogDebug("ForNode sequence node type: %T", n.sequence)
// Special handling for filter nodes in for loops to aid debugging
if filterNode, ok := n.sequence.(*FilterNode); ok {
LogDebug("ForNode sequence is a FilterNode with filter: %s", filterNode.filter)
}
}
// Special handling for FilterNode to improve rendering in for loops
if filterNode, ok := n.sequence.(*FilterNode); ok {
if IsDebugEnabled() {
LogDebug("ForNode: direct processing of filter node: %s", filterNode.filter)
}
// Get the base value first
baseNode, filterChain, err := ctx.DetectFilterChain(filterNode)
if err != nil {
return err
}
// Evaluate the base value
baseValue, err := ctx.EvaluateExpression(baseNode)
if err != nil {
return err
}
if IsDebugEnabled() {
LogDebug("ForNode: base value type: %T, filter chain length: %d", baseValue, len(filterChain))
}
// Apply each filter in the chain
result := baseValue
for _, filter := range filterChain {
if IsDebugEnabled() {
LogDebug("ForNode: applying filter: %s", filter.name)
}
// Apply the filter
result, err = ctx.ApplyFilter(filter.name, result, filter.args...)
if err != nil {
return err
}
if IsDebugEnabled() {
LogDebug("ForNode: after filter %s, result type: %T", filter.name, result)
}
}
// Use the filtered result directly
return n.renderForLoop(w, ctx, result)
}
// Standard evaluation for other types of sequences
seq, err := ctx.EvaluateExpression(n.sequence)
if err != nil {
return err
}
// WORKAROUND: When a filter is used directly in a for loop sequence like:
// {% for item in items|sort %}, the parser currently registers the sequence
// as a VariableNode with a name like "items|sort" instead of properly parsing
// it as a FilterNode. This workaround handles this parsing deficiency.
if varNode, ok := n.sequence.(*VariableNode); ok {
// Check if the variable contains a filter indicator (|)
if strings.Contains(varNode.name, "|") {
parts := strings.SplitN(varNode.name, "|", 2)
if len(parts) == 2 {
baseVar := parts[0]
filterName := parts[1]
if IsDebugEnabled() {
LogDebug("ForNode: Detected inline filter reference: var=%s, filter=%s", baseVar, filterName)
}
// Get the base value
baseValue, _ := ctx.GetVariable(baseVar)
// Apply the filter
if baseValue != nil {
if IsDebugEnabled() {
LogDebug("ForNode: Applying filter %s to %T manually", filterName, baseValue)
}
// Try to apply the filter
if ctx.env != nil {
filterFunc, found := ctx.env.filters[filterName]
if found {
filteredResult, err := filterFunc(baseValue)
if err == nil && filteredResult != nil {
if IsDebugEnabled() {
LogDebug("ForNode: Manual filter application successful")
}
seq = filteredResult
}
}
}
}
}
}
}
if IsDebugEnabled() {
LogDebug("ForNode: sequence after evaluation: %T", seq)
}
return n.renderForLoop(w, ctx, seq)
}
// renderForLoop handles the actual for loop iteration after sequence is determined
func (n *ForNode) renderForLoop(w io.Writer, ctx *RenderContext, seq interface{}) error {
// If sequence is nil or invalid, render the else branch
if seq == nil {
if n.elseBranch != nil {
for _, node := range n.elseBranch {
err := node.Render(w, ctx)
if err != nil {
return err
}
}
}
return nil
}
// Get the value as a reflect.Value for iteration
val := reflect.ValueOf(seq)
// Create a new context for the loop variables
loopCtx := ctx
// Keep track of loop variables
loopVars := map[string]interface{}{
"loop": map[string]interface{}{
"index": 0,
"index0": 0,
"revindex": 0,
"revindex0": 0,
"first": false,
"last": false,
"length": 0,
},
}
// Variables to track iteration state
length := 0
isIterable := true
switch val.Kind() {
case reflect.Slice, reflect.Array:
length = val.Len()
// Convert typed slices to []interface{} for consistent iteration
// This is essential for for-loop compatibility with filter results
if val.Type().Elem().Kind() != reflect.Interface {
// Debug logging for this conversion operation
if IsDebugEnabled() {
LogDebug("Converting %s to []interface{} for for-loop compatibility", val.Type())
}
// Create a new []interface{} and copy all values
interfaceSlice := make([]interface{}, length)
for i := 0; i < length; i++ {
if val.Index(i).CanInterface() {
interfaceSlice[i] = val.Index(i).Interface()
}
}
// Replace the original sequence with our new interface slice
seq = interfaceSlice
val = reflect.ValueOf(seq)
}
case reflect.Map:
length = val.Len()
case reflect.String:
length = val.Len()
default:
// For other types, try to convert to an interface slice
// to support custom iterables
if strVal, ok := seq.(string); ok {
// Convert string to runes for iteration
length = len([]rune(strVal))
} else if seqSlice, ok := seq.([]interface{}); ok {
// Already an interface slice
length = len(seqSlice)
seq = seqSlice
val = reflect.ValueOf(seq)
} else {
// Not directly iterable
isIterable = false
}
}
// If not iterable or length is 0, render the else branch if available
if !isIterable || length == 0 {
if n.elseBranch != nil {
for _, node := range n.elseBranch {
err := node.Render(w, ctx)
if err != nil {
return err
}
}
}
return nil
}
// Update loop.length
loopVars["loop"].(map[string]interface{})["length"] = length
// Iterate based on the type
switch val.Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < val.Len(); i++ {
// Set the loop variables
loopVars["loop"].(map[string]interface{})["index"] = i + 1
loopVars["loop"].(map[string]interface{})["index0"] = i
loopVars["loop"].(map[string]interface{})["revindex"] = length - i
loopVars["loop"].(map[string]interface{})["revindex0"] = length - i - 1
loopVars["loop"].(map[string]interface{})["first"] = i == 0
loopVars["loop"].(map[string]interface{})["last"] = i == length-1
// Set the value variable
if val.Index(i).CanInterface() {
loopCtx.SetVariable(n.valueVar, val.Index(i).Interface())
} else {
loopCtx.SetVariable(n.valueVar, nil)
}
// Set the key variable if provided
if n.keyVar != "" {
loopCtx.SetVariable(n.keyVar, i)
}
// Set the loop variables
loopCtx.SetVariable("loop", loopVars["loop"])
// Render the body
for _, node := range n.body {
err := node.Render(w, loopCtx)
if err != nil {
return err
}
}
}
case reflect.Map:
keys := val.MapKeys()
for i, key := range keys {
// Set the loop variables
loopVars["loop"].(map[string]interface{})["index"] = i + 1
loopVars["loop"].(map[string]interface{})["index0"] = i
loopVars["loop"].(map[string]interface{})["revindex"] = length - i
loopVars["loop"].(map[string]interface{})["revindex0"] = length - i - 1
loopVars["loop"].(map[string]interface{})["first"] = i == 0
loopVars["loop"].(map[string]interface{})["last"] = i == length-1
// Set the value variable
if val.MapIndex(key).CanInterface() {
loopCtx.SetVariable(n.valueVar, val.MapIndex(key).Interface())
} else {
loopCtx.SetVariable(n.valueVar, nil)
}
// Set the key variable if provided
if n.keyVar != "" {
if key.CanInterface() {
loopCtx.SetVariable(n.keyVar, key.Interface())
} else {
loopCtx.SetVariable(n.keyVar, nil)
}
}
// Set the loop variables
loopCtx.SetVariable("loop", loopVars["loop"])
// Render the body
for _, node := range n.body {
err := node.Render(w, loopCtx)
if err != nil {
return err
}
}
}
case reflect.String:
for i, char := range val.String() {
// Set the loop variables
loopVars["loop"].(map[string]interface{})["index"] = i + 1
loopVars["loop"].(map[string]interface{})["index0"] = i
loopVars["loop"].(map[string]interface{})["revindex"] = length - i
loopVars["loop"].(map[string]interface{})["revindex0"] = length - i - 1
loopVars["loop"].(map[string]interface{})["first"] = i == 0
loopVars["loop"].(map[string]interface{})["last"] = i == length-1
// Set the value variable
loopCtx.SetVariable(n.valueVar, string(char))
// Set the key variable if provided
if n.keyVar != "" {
loopCtx.SetVariable(n.keyVar, i)
}
// Set the loop variables
loopCtx.SetVariable("loop", loopVars["loop"])
// Render the body
for _, node := range n.body {
err := node.Render(w, loopCtx)
if err != nil {
return err
}
}
}
}
return nil
}
// BlockNode represents a block definition
type BlockNode struct {
name string
body []Node
line int
}
func (n *BlockNode) Type() NodeType {
return NodeBlock
}
func (n *BlockNode) Line() int {
return n.line
}
// Release returns a BlockNode to the pool
func (n *BlockNode) Release() {
ReleaseBlockNode(n)
}
// Render renders the block node
func (n *BlockNode) Render(w io.Writer, ctx *RenderContext) error {
// Determine which content to use - from context blocks or default
var content []Node
// Store the current block content as parent content if needed
// This is critical for multi-level inheritance
if _, exists := ctx.parentBlocks[n.name]; !exists {
// First time we've seen this block - store its original content
// This needs to happen for any block, not just in extending templates
if blockContent, ok := ctx.blocks[n.name]; ok && len(blockContent) > 0 {
// Store the content from blocks
ctx.parentBlocks[n.name] = blockContent
} else {
// Otherwise store the default body
ctx.parentBlocks[n.name] = n.body
}
}
// Now get the content to render
if blockContent, ok := ctx.blocks[n.name]; ok && len(blockContent) > 0 {
content = blockContent
} else {
// Otherwise, use the default content from this block node
content = n.body
}
// Save the current block for parent() function support
previousBlock := ctx.currentBlock
ctx.currentBlock = n
// Create an isolated context for rendering this block
// This prevents parent() from accessing the wrong block context
blockCtx := ctx
// Render the appropriate content
for _, node := range content {
err := node.Render(w, blockCtx)
if err != nil {
return err
}
}
// Restore the previous block
ctx.currentBlock = previousBlock
return nil
}
// ExtendsNode represents an extends directive
type ExtendsNode struct {
parent Node
line int
}
func (n *ExtendsNode) Type() NodeType {
return NodeExtends
}
func (n *ExtendsNode) Line() int {
return n.line
}
// Release returns an ExtendsNode to the pool
func (n *ExtendsNode) Release() {
ReleaseExtendsNode(n)
}
// Implement Node interface for ExtendsNode
func (n *ExtendsNode) Render(w io.Writer, ctx *RenderContext) error {
// Flag that this template extends another
ctx.extending = true
// Get the parent template name
templateExpr, err := ctx.EvaluateExpression(n.parent)
if err != nil {
return err
}
templateName := ctx.ToString(templateExpr)
// Load the parent template
if ctx.engine == nil {
return fmt.Errorf("no template engine available to load parent template: %s", templateName)
}
// Handle relative paths for templates
resolvedName := templateName
if strings.HasPrefix(templateName, "./") || strings.HasPrefix(templateName, "../") {
// Get the directory of the current template
currentTemplate := ctx.engine.currentTemplate
if currentTemplate != "" {
// Extract the directory part of the current template
currentDir := filepath.Dir(currentTemplate)
// Join the directory with the relative path
resolvedName = filepath.Join(currentDir, templateName)
}
}
// Load the parent template with resolved path
parentTemplate, err := ctx.engine.Load(resolvedName)
if err != nil {
// Only try the fallback if the template was not found AND the paths are different
if errors.Is(err, ErrTemplateNotFound) && resolvedName != templateName {
parentTemplate, err = ctx.engine.Load(templateName)
if err != nil {
return err
}
} else {
// For any other error (including syntax errors), return immediately
return err
}
}
// Blocks from child template are registered to the parent context
// Create a new context for the parent template, but with our child blocks
// This ensures the parent template knows it's being extended and preserves our blocks
parentCtx := NewRenderContext(ctx.env, ctx.context, ctx.engine)
parentCtx.extending = true // Flag that the parent is being extended
// Pass along the parent template as lastLoadedTemplate for relative path resolution
parentCtx.lastLoadedTemplate = parentTemplate
// Ensure the context is released even if an error occurs
defer parentCtx.Release()
// First, copy any existing parent blocks to maintain the inheritance chain
// This allows for multi-level parent() calls to work properly
for name, nodes := range ctx.parentBlocks {
// Copy to the new context to preserve the inheritance chain
parentCtx.parentBlocks[name] = nodes
}
// Extract blocks from the parent template and store them as parent blocks
// for any blocks defined in the child but not yet in the parent chain
if rootNode, ok := parentTemplate.nodes.(*RootNode); ok {
// Use recursive collection to find all blocks in parent template
parentBlocks := make(map[string][]Node)
collectBlocks(rootNode, parentBlocks)
// Store parent blocks that we don't already have
for blockName, blockBody := range parentBlocks {
if _, exists := parentCtx.parentBlocks[blockName]; !exists {
parentCtx.parentBlocks[blockName] = blockBody
}
}
}
// Finally, copy all block definitions from the child context
// These are the blocks that will actually be rendered
for name, nodes := range ctx.blocks {
parentCtx.blocks[name] = nodes
}
// Render the parent template with the updated context
return parentTemplate.nodes.Render(w, parentCtx)
}
// IncludeNode represents an include directive
type IncludeNode struct {
template Node
variables map[string]Node
ignoreMissing bool
only bool
sandboxed bool
line int
}
func (n *IncludeNode) Type() NodeType {
return NodeInclude
}
func (n *IncludeNode) Line() int {
return n.line
}
// Release returns an IncludeNode to the pool
func (n *IncludeNode) Release() {
ReleaseIncludeNode(n)
}
// Implement Node interface for IncludeNode
func (n *IncludeNode) Render(w io.Writer, ctx *RenderContext) error {
// Get the template name
templateExpr, err := ctx.EvaluateExpression(n.template)
if err != nil {
return err
}
templateName := ctx.ToString(templateExpr)
// Load the template
if ctx.engine == nil {
return fmt.Errorf("no template engine available to load included template: %s", templateName)
}
// Handle relative paths for templates
resolvedName := templateName
if strings.HasPrefix(templateName, "./") || strings.HasPrefix(templateName, "../") {
// Get the directory of the current template
currentTemplate := ctx.engine.currentTemplate
if currentTemplate != "" {
// Extract the directory part of the current template
currentDir := filepath.Dir(currentTemplate)
// Join the directory with the relative path
resolvedName = filepath.Join(currentDir, templateName)
}
}
// Load the template with resolved path
template, err := ctx.engine.Load(resolvedName)
if err != nil {
// Only try the fallback if the template was not found AND the paths are different
if errors.Is(err, ErrTemplateNotFound) && resolvedName != templateName {
template, err = ctx.engine.Load(templateName)
if err != nil {
if n.ignoreMissing && errors.Is(err, ErrTemplateNotFound) {
return nil
}
return err
}
} else {
if n.ignoreMissing && errors.Is(err, ErrTemplateNotFound) {
return nil
}
// For any other error (including syntax errors), return immediately
return err
}
}
// Create optimized context handling for includes
// Fast path: if no special handling needed and not sandboxed, render with current context
if !n.only && !n.sandboxed && len(n.variables) == 0 {
// Clone the context but with the new lastLoadedTemplate
includeCtx := ctx.Clone()
includeCtx.lastLoadedTemplate = template
defer includeCtx.Release()
return template.nodes.Render(w, includeCtx)
}
// Need a new context for 'only' mode, sandboxed mode, or with variables
includeCtx := ctx
if n.only || n.sandboxed {
var contextVars map[string]interface{}
if n.only {
// Only mode - create empty context
contextVars = make(map[string]interface{}, len(n.variables))
} else {
// For sandboxed mode but not 'only' mode, copy the parent context
contextVars = make(map[string]interface{}, len(ctx.context)+len(n.variables))
for k, v := range ctx.context {
contextVars[k] = v
}
}
// Create a new context
includeCtx = NewRenderContext(ctx.env, contextVars, ctx.engine)
// Set the template as the lastLoadedTemplate for relative path resolutionn includeCtx.lastLoadedTemplate = template
defer includeCtx.Release()
// If sandboxed, enable sandbox mode
if n.sandboxed {
includeCtx.sandboxed = true
// Check if a security policy is defined
if ctx.env.securityPolicy == nil {
return fmt.Errorf("cannot use sandboxed include without a security policy")
}
}
}
// Pre-evaluate all variables before setting them
if len(n.variables) > 0 {
for name, valueNode := range n.variables {
value, err := ctx.EvaluateExpression(valueNode)
if err != nil {
return err
}
includeCtx.SetVariable(name, value)
}
}
// Render the included template
err = template.nodes.Render(w, includeCtx)
return err
}
// SetNode represents a variable assignment
type SetNode struct {
name string
value Node
line int
}
func (n *SetNode) Type() NodeType {
return NodeSet
}
func (n *SetNode) Line() int {
return n.line
}
// Release returns a SetNode to the pool
func (n *SetNode) Release() {
ReleaseSetNode(n)
}
// Render renders the set node
func (n *SetNode) Render(w io.Writer, ctx *RenderContext) error {
// Evaluate the value
value, err := ctx.EvaluateExpression(n.value)
if err != nil {
return err
}
// Set the variable in the context
ctx.SetVariable(n.name, value)
return nil
}
// DoNode represents a do tag which evaluates an expression without printing the result
type DoNode struct {
expression Node
line int
}
// NewDoNode creates a new DoNode
func NewDoNode(expression Node, line int) *DoNode {
return GetDoNode(expression, line)
}
func (n *DoNode) Type() NodeType {
return NodeDo
}
func (n *DoNode) Line() int {
return n.line
}
// Release returns a DoNode to the pool
func (n *DoNode) Release() {
ReleaseDoNode(n)
}
// Render evaluates the expression but doesn't write anything
func (n *DoNode) Render(w io.Writer, ctx *RenderContext) error {
// Evaluate the expression but ignore the result
_, err := ctx.EvaluateExpression(n.expression)
return err
}
// CommentNode represents a comment
type CommentNode struct {
content string
line int
}
func (n *CommentNode) Type() NodeType {
return NodeComment
}
func (n *CommentNode) Line() int {
return n.line
}
// Release returns a CommentNode to the pool
func (n *CommentNode) Release() {
ReleaseCommentNode(n)
}
// Render renders the comment node (does nothing, as comments are not rendered)
func (n *CommentNode) Render(w io.Writer, ctx *RenderContext) error {
// Comments are not rendered
return nil
}
// MacroNode represents a macro definition
type MacroNode struct {
name string
params []string
defaults map[string]Node
body []Node
line int
}
func (n *MacroNode) Type() NodeType {
return NodeMacro
}
func (n *MacroNode) Line() int {
return n.line
}
// Release returns a MacroNode to the pool
func (n *MacroNode) Release() {
ReleaseMacroNode(n)
}
// Render renders the macro node
func (n *MacroNode) Render(w io.Writer, ctx *RenderContext) error {
// Register the macro in the context
ctx.macros[n.name] = n
return nil
}
// processMacroTemplate performs a simple regex-based rewrite of the macro template
func processMacroTemplate(source string) string {
// Replace attribute references with quoted ones for the common HTML attributes
result := source