From f4307541c47412f73667a1019994a5b1209c0513 Mon Sep 17 00:00:00 2001 From: Elara6331 Date: Mon, 18 Dec 2023 11:59:39 -0800 Subject: [PATCH] Add the ability to disable whitespace mutations --- namespace.go | 23 ++++++++++++++++++----- parse.go | 4 +++- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/namespace.go b/namespace.go index 1bdfb62..0d18337 100644 --- a/namespace.go +++ b/namespace.go @@ -9,15 +9,20 @@ type Namespace struct { vars map[string]any tags map[string]Tag - escapeHTML *bool + // WhitespaceMutations enables postprocessing to remove whitespace where it isn't needed + // to make the resulting document look better. Postprocessing is only done oncewhen the + // template is parsed, so it will not affect performance. (default: true) + WhitespaceMutations bool + escapeHTML *bool } // New returns a new template namespace func New() *Namespace { return &Namespace{ - tmpls: map[string]Template{}, - vars: map[string]any{}, - tags: map[string]Tag{}, + tmpls: map[string]Template{}, + vars: map[string]any{}, + tags: map[string]Tag{}, + WhitespaceMutations: true, } } @@ -49,7 +54,7 @@ func (n *Namespace) WithTagMap(m map[string]Tag) *Namespace { return n } -// WithVarMap turns HTML escaping on or off for the namespace +// WithEscapeHTML turns HTML escaping on or off for the namespace func (n *Namespace) WithEscapeHTML(b bool) *Namespace { n.mu.Lock() defer n.mu.Unlock() @@ -57,6 +62,14 @@ func (n *Namespace) WithEscapeHTML(b bool) *Namespace { return n } +// WithWhitespaceMutations turns whitespace mutations on or off for the namespace +func (n *Namespace) WithWhitespaceMutations(b bool) *Namespace { + n.mu.Lock() + defer n.mu.Unlock() + n.WhitespaceMutations = true + return n +} + // GetTemplate tries to get a template from the namespace's template map. // If it finds the template, it returns the template and true. If it // doesn't find it, it returns nil and false. diff --git a/parse.go b/parse.go index 79438f1..f595ea1 100644 --- a/parse.go +++ b/parse.go @@ -39,7 +39,9 @@ func (n *Namespace) ParseWithName(name string, r io.Reader) (Template, error) { vars: map[string]any{}, } - performWhitespaceMutations(t.ast) + if n.WhitespaceMutations { + performWhitespaceMutations(t.ast) + } n.mu.Lock() defer n.mu.Unlock()