Skip to content

Commit

Permalink
fix: Do not HTML escape in fallback JSON mode (#17)
Browse files Browse the repository at this point in the history
* fix: Do not HTML escape in fallback JSON mode

When a template specifies `{{{.}}}` or otherwise
falls back to the json.Marshal case, it needs to avoid
escaping &, <, and > characters. This is especially
important because it is common to have URLs with query
strings in object properties and you get a different behavior
from referencing the property vs the parent object.
  • Loading branch information
obs-gh-catherman authored Oct 15, 2024
1 parent a241516 commit 976d216
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions mustache.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,8 +312,19 @@ func print(w io.Writer, v interface{}, needEscape escapeType) {
case float32, float64:
output = fmt.Sprintf("%g", v)
default:
obj, _ := json.Marshal(v)
output = string(obj)
// The default json encoder will HTML escape &, <, and >.
// Since we explicitly handle escape by user directive, let's make
// sure that doesn't happen in the case we just got asked to
// marshal a full object (like via `{{{.}}}`).
var b bytes.Buffer
enc := json.NewEncoder(&b)
enc.SetEscapeHTML(false)

_ = enc.Encode(v)
output = b.String()

// Sadly, the built-in encoder will add a newline so we need to remove that.
output = strings.TrimRight(output, "\n")
}
}

Expand Down

0 comments on commit 976d216

Please sign in to comment.