Escape input to template hash

This commit is contained in:
Andinus 2024-11-16 17:33:15 +05:30
parent 0acc608e47
commit 07adf2d49e
Signed by: andinus
GPG Key ID: B67D55D482A799FD

@ -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 {