Skip to content

Commit

Permalink
strings: fix Truncate behavior for formatted html
Browse files Browse the repository at this point in the history
Before this fix, strings.Truncate would erroneously re-include
attributes from the opening tag in the closing tag when closing
formatted html, due to a bug in how tagnames were extracted from the
regex capture group for html tags used in `truncate.go`. This change
ensures that only the tagname is retained and all attributes are discarded
when storing the tags for closing them later.

Fixes #10399
  • Loading branch information
khayyamsaleem authored and bep committed Mar 1, 2023
1 parent 2a61910 commit c0d15a2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
5 changes: 3 additions & 2 deletions tpl/strings/truncate.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"html"
"html/template"
"regexp"
"strings"
"unicode"
"unicode/utf8"

Expand Down Expand Up @@ -92,12 +93,12 @@ func (ns *Namespace) Truncate(s any, options ...any) (template.HTML, error) {
}

if isHTML {
// Make sure we keep tag of HTML tags
// Make sure we keep tagname of HTML tags
slice := text[i:]
m := tagRE.FindStringSubmatchIndex(slice)
if len(m) > 0 && m[0] == 0 {
nextTag = i + m[1]
tagname := slice[m[4]:m[5]]
tagname := strings.Fields(slice[m[4]:m[5]])[0]
lastWordIndex = lastNonSpace
_, singlet := htmlSinglets[tagname]
if !singlet && m[6] == -1 {
Expand Down
17 changes: 17 additions & 0 deletions tpl/strings/truncate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,23 @@ func TestTruncate(t *testing.T) {
{3, template.HTML(strings.Repeat("<p>P</p>", 20)), nil, template.HTML("<p>P</p><p>P</p><p>P …</p>"), false},
{18, template.HTML("<p>test <b>hello</b> test something</p>"), nil, template.HTML("<p>test <b>hello</b> test …</p>"), false},
{4, template.HTML("<p>a<b><i>b</b>c d e</p>"), nil, template.HTML("<p>a<b><i>b</b>c …</p>"), false},
{
42,
template.HTML(`With strangely formatted
<a
href="#"
target="_blank"
>HTML</a
>
inside.`),
nil,
template.HTML(`With strangely formatted
<a
href="#"
target="_blank"
>HTML …</a>`),
false,
},
{10, nil, nil, template.HTML(""), true},
{nil, nil, nil, template.HTML(""), true},
}
Expand Down

0 comments on commit c0d15a2

Please sign in to comment.