diff options
author | Khayyam Saleem <hello@khayyam.me> | 2023-01-27 11:57:31 -0500 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2023-03-01 17:59:50 +0100 |
commit | c0d15a2897be0bc9f6df2514f5a477b6df1fa0e5 (patch) | |
tree | 91cc3691013b51aac6d3b3a41b582be08e4150c9 /tpl | |
parent | 2a61910e824ad2bb223bca65c03460e83bb841e0 (diff) |
strings: fix Truncate behavior for formatted html
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
Diffstat (limited to 'tpl')
-rw-r--r-- | tpl/strings/truncate.go | 5 | ||||
-rw-r--r-- | tpl/strings/truncate_test.go | 17 |
2 files changed, 20 insertions, 2 deletions
diff --git a/tpl/strings/truncate.go b/tpl/strings/truncate.go index e8da7b84b..efa910618 100644 --- a/tpl/strings/truncate.go +++ b/tpl/strings/truncate.go @@ -18,6 +18,7 @@ import ( "html" "html/template" "regexp" + "strings" "unicode" "unicode/utf8" @@ -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 { diff --git a/tpl/strings/truncate_test.go b/tpl/strings/truncate_test.go index 62125e1b4..e2339aa27 100644 --- a/tpl/strings/truncate_test.go +++ b/tpl/strings/truncate_test.go @@ -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}, } |