Skip to content

Commit 22cd89a

Browse files
kroppbep
authored andcommitted
Make chomp return the type it receives
fixes #2187
1 parent db4b7a5 commit 22cd89a

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

‎tpl/strings/strings.go‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,13 +78,20 @@ func (ns *Namespace) CountWords(s interface{}) (int, error) {
7878
}
7979

8080
// Chomp returns a copy of s with all trailing newline characters removed.
81-
func (ns *Namespace) Chomp(s interface{}) (template.HTML, error) {
81+
func (ns *Namespace) Chomp(s interface{}) (interface{}, error) {
8282
ss, err := cast.ToStringE(s)
8383
if err != nil {
8484
return "", err
8585
}
8686

87-
return template.HTML(_strings.TrimRight(ss, "\r\n")), nil
87+
res := _strings.TrimRight(ss, "\r\n")
88+
switch s.(type) {
89+
case template.HTML:
90+
return template.HTML(res), nil
91+
default:
92+
return res, nil
93+
}
94+
8895
}
8996

9097
// Contains reports whether substr is in s.

‎tpl/strings/strings_test.go‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import (
1919
"testing"
2020

2121
"github.com/gohugoio/hugo/deps"
22+
"github.com/spf13/cast"
2223
"github.com/spf13/viper"
2324
"github.com/stretchr/testify/assert"
2425
"github.com/stretchr/testify/require"
@@ -35,12 +36,12 @@ func TestChomp(t *testing.T) {
3536
s interface{}
3637
expect interface{}
3738
}{
38-
{"\n a\n", template.HTML("\n a")},
39-
{"\n a\n\n", template.HTML("\n a")},
40-
{"\n a\r\n", template.HTML("\n a")},
41-
{"\n a\n\r\n", template.HTML("\n a")},
42-
{"\n a\r\r", template.HTML("\n a")},
43-
{"\n a\r", template.HTML("\n a")},
39+
{"\n a\n", "\n a"},
40+
{"\n a\n\n", "\n a"},
41+
{"\n a\r\n", "\n a"},
42+
{"\n a\n\r\n", "\n a"},
43+
{"\n a\r\r", "\n a"},
44+
{"\n a\r", "\n a"},
4445
// errors
4546
{tstNoStringer{}, false},
4647
} {
@@ -55,6 +56,11 @@ func TestChomp(t *testing.T) {
5556

5657
require.NoError(t, err, errMsg)
5758
assert.Equal(t, test.expect, result, errMsg)
59+
60+
// repeat the check with template.HTML input
61+
result, err = ns.Chomp(template.HTML(cast.ToString(test.s)))
62+
require.NoError(t, err, errMsg)
63+
assert.Equal(t, template.HTML(cast.ToString(test.expect)), result, errMsg)
5864
}
5965
}
6066

0 commit comments

Comments
 (0)