-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwhitespace.go
71 lines (58 loc) · 1.68 KB
/
whitespace.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package twig
import (
"io"
"regexp"
"strings"
)
// trimLeadingWhitespace removes leading whitespace from a string
func trimLeadingWhitespace(s string) string {
return strings.TrimLeft(s, " \t\n\r")
}
// trimTrailingWhitespace removes trailing whitespace from a string
func trimTrailingWhitespace(s string) string {
return strings.TrimRight(s, " \t\n\r")
}
// SpacelessNode represents a {% spaceless %} ... {% endspaceless %} block
type SpacelessNode struct {
body []Node
line int
}
// NewSpacelessNode creates a new spaceless node
func NewSpacelessNode(body []Node, line int) *SpacelessNode {
return &SpacelessNode{
body: body,
line: line,
}
}
// Render renders the node to a writer
func (n *SpacelessNode) Render(w io.Writer, ctx *RenderContext) error {
// First, render the content to a string using a buffer
var buf StringBuffer
for _, node := range n.body {
if err := node.Render(&buf, ctx); err != nil {
return err
}
}
// Get the rendered content as a string
content := buf.String()
// Apply spaceless processing (remove whitespace between HTML tags)
result := removeWhitespaceBetweenTags(content)
// Write the processed result
_, err := w.Write([]byte(result))
return err
}
// Line returns the line number of the node
func (n *SpacelessNode) Line() int {
return n.line
}
// Type returns the node type
func (n *SpacelessNode) Type() NodeType {
return NodeSpaceless
}
// removeWhitespaceBetweenTags removes whitespace between HTML tags
// but preserves whitespace between words
func removeWhitespaceBetweenTags(content string) string {
// This regex matches whitespace between HTML tags only
re := regexp.MustCompile(">\\s+<")
return re.ReplaceAllString(content, "><")
}