Skip to content

Commit

Permalink
HTML: keep original quote when isXML is set; merge isXML with mustQuo…
Browse files Browse the repository at this point in the history
…te; don't add quotes if not originally present
  • Loading branch information
tdewolff committed Feb 17, 2024
1 parent 3b2a162 commit 0d6dfe1
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 13 deletions.
12 changes: 4 additions & 8 deletions html/util.go
Expand Up @@ -6,7 +6,7 @@ var (
)

// EscapeAttrVal returns the escaped attribute value bytes with quotes. Either single or double quotes are used, whichever is shorter. If there are no quotes present in the value and the value is in HTML (not XML), it will return the value without quotes.
func EscapeAttrVal(buf *[]byte, b []byte, origQuote byte, mustQuote, isXML bool) []byte {
func EscapeAttrVal(buf *[]byte, b []byte, origQuote byte, mustQuote bool) []byte {
singles := 0
doubles := 0
unquoted := true
Expand All @@ -20,9 +20,9 @@ func EscapeAttrVal(buf *[]byte, b []byte, origQuote byte, mustQuote, isXML bool)
}
}
}
if unquoted && (!mustQuote || origQuote == 0) && !isXML {
if unquoted && (!mustQuote || origQuote == 0) {
return b
} else if singles == 0 && origQuote == '\'' && !isXML || doubles == 0 && origQuote == '"' {
} else if singles == 0 && origQuote == '\'' || doubles == 0 && origQuote == '"' {
if len(b)+2 > cap(*buf) {
*buf = make([]byte, 0, len(b)+2)
}
Expand All @@ -36,14 +36,10 @@ func EscapeAttrVal(buf *[]byte, b []byte, origQuote byte, mustQuote, isXML bool)
n := len(b) + 2
var quote byte
var escapedQuote []byte
if singles >= doubles || isXML {
if singles > doubles || singles == doubles && origQuote != '\'' {
n += doubles * 4
quote = '"'
escapedQuote = doubleQuoteEntityBytes
if singles == doubles && origQuote == '\'' && !isXML {
quote = '\''
escapedQuote = singleQuoteEntityBytes
}
} else {
n += singles * 4
quote = '\''
Expand Down
10 changes: 5 additions & 5 deletions html/util_test.go
Expand Up @@ -36,7 +36,7 @@ func TestEscapeAttrVal(t *testing.T) {
if len(b) > 1 && (b[0] == '"' || b[0] == '\'') && b[0] == b[len(b)-1] {
b = b[1 : len(b)-1]
}
val := EscapeAttrVal(&buf, b, quote, false, false)
val := EscapeAttrVal(&buf, b, quote, false)
test.String(t, string(val), tt.expected)
})
}
Expand All @@ -48,9 +48,9 @@ func TestEscapeAttrValXML(t *testing.T) {
expected string
}{
{`"xyz"`, `"xyz"`},
{`xyz`, `"xyz"`},
{`'xyz'`, `"xyz"`},
{``, `""`},
{`'xyz'`, `'xyz'`},
{`xyz`, `xyz`},
{``, ``},
}
var buf []byte
for _, tt := range escapeAttrValTests {
Expand All @@ -63,7 +63,7 @@ func TestEscapeAttrValXML(t *testing.T) {
if len(b) > 1 && (b[0] == '"' || b[0] == '\'') && b[0] == b[len(b)-1] {
b = b[1 : len(b)-1]
}
val := EscapeAttrVal(&buf, b, quote, false, true)
val := EscapeAttrVal(&buf, b, quote, true)
test.String(t, string(val), tt.expected)
})
}
Expand Down

0 comments on commit 0d6dfe1

Please sign in to comment.