Allow setting escapeHTML for an entire namespace

This commit is contained in:
Elara 2023-11-01 11:39:28 -07:00
parent e68190ca6a
commit 38420f5c6a
2 changed files with 30 additions and 3 deletions

View File

@ -29,6 +29,8 @@ type Namespace struct {
tmpls map[string]Template
vars map[string]reflect.Value
tags map[string]Tag
escapeHTML *bool
}
// New returns a new template namespace
@ -69,6 +71,14 @@ func (n *Namespace) WithTagMap(m map[string]Tag) *Namespace {
return n
}
// WithVarMap turns HTML escaping on or off for the namespace
func (n *Namespace) WithEscapeHTML(b bool) *Namespace {
n.mu.Lock()
defer n.mu.Unlock()
n.escapeHTML = &b
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.
@ -94,3 +104,10 @@ func (n *Namespace) getTag(name string) (Tag, bool) {
t, ok := n.tags[name]
return t, ok
}
// getEscapeHTML returns the namespace's escapeHTML value
func (n *Namespace) getEscapeHTML() *bool {
n.mu.Lock()
defer n.mu.Unlock()
return n.escapeHTML
}

View File

@ -58,7 +58,7 @@ type Template struct {
name string
ast []ast.Node
escapeHTML bool
escapeHTML *bool
tags map[string]Tag
vars map[string]reflect.Value
@ -90,7 +90,7 @@ func (t Template) WithTagMap(m map[string]Tag) Template {
// The HTML escaping functionality is NOT context-aware.
// Using the HTML type allows you to get around the escaping if needed.
func (t Template) WithEscapeHTML(b bool) Template {
t.escapeHTML = true
t.escapeHTML = &b
return t
}
@ -140,10 +140,20 @@ func (t *Template) execute(w io.Writer, nodes []ast.Node, local map[string]any)
return nil
}
func (t *Template) getEscapeHTML() bool {
if t.escapeHTML != nil {
return *t.escapeHTML
} else if t.ns.escapeHTML != nil {
return *t.ns.getEscapeHTML()
} else {
return false
}
}
func (t *Template) toString(v any) string {
if h, ok := v.(HTML); ok {
return string(h)
} else if t.escapeHTML {
} else if t.getEscapeHTML() {
return html.EscapeString(fmt.Sprint(v))
}
return fmt.Sprint(v)