From 07adf2d49e7eff6d6e6c2b963e760807ef597ffb Mon Sep 17 00:00:00 2001 From: Andinus Date: Sat, 16 Nov 2024 17:33:15 +0530 Subject: [PATCH] Escape input to template hash --- template_nest.go | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/template_nest.go b/template_nest.go index 8f6083d..6238585 100644 --- a/template_nest.go +++ b/template_nest.go @@ -2,6 +2,7 @@ package templatenest import ( "fmt" + "html" "io/ioutil" "os" "path/filepath" @@ -25,12 +26,13 @@ type Option struct { TokenEscapeChar string // Escapes a token delimiter, i.e. if set to '\' then variables that have '\' prefix won't be replaced DefaultsNamespaceChar string Defaults Hash // Provide a hash of default values that are substituted if template hash does not provide a value - defaultsFlat Hash + NoEscapeInput bool // By default all template values are html escaped } type TemplateNest struct { - option Option - cache map[string]TemplateFileIndex + option Option + defaultsFlat Hash + cache map[string]TemplateFileIndex } // TemplateFileIndex represents an indexed template file. @@ -83,12 +85,11 @@ func New(opts Option) (*TemplateNest, error) { opts.Defaults = make(map[string]interface{}) } - opts.defaultsFlat = FlattenMap(opts.Defaults, "", opts.DefaultsNamespaceChar) - // Initialize TemplateNest with the final options. nest := &TemplateNest{ - option: opts, - cache: make(map[string]TemplateFileIndex), + option: opts, + cache: make(map[string]TemplateFileIndex), + defaultsFlat: FlattenMap(opts.Defaults, "", opts.DefaultsNamespaceChar), } // Walk through the template directory and index the templates. @@ -263,7 +264,10 @@ func (nest *TemplateNest) Render(toRender interface{}) (string, error) { return fmt.Sprintf("%t", v), nil case string: - return v, nil + if nest.option.NoEscapeInput { + return v, nil + } + return html.EscapeString(v), nil case float64, int, int64: return fmt.Sprintf("%v", v), nil @@ -337,7 +341,7 @@ func (nest *TemplateNest) Render(toRender interface{}) (string, error) { replacement := "" value, exists := v[variable.Name] - defaultValue, defaultExists := nest.option.defaultsFlat[variable.Name] + defaultValue, defaultExists := nest.defaultsFlat[variable.Name] if exists || defaultExists { if !exists {