mirror of
https://github.com/gohugoio/hugo.git
synced 2025-08-29 22:29:56 +02:00
tpl/strings: strings.RuneCount
This commit is contained in:
committed by
Bjørn Erik Pedersen
parent
c3115292a7
commit
019bd5576b
@@ -41,6 +41,11 @@ func init() {
|
||||
[][2]string{},
|
||||
)
|
||||
|
||||
ns.AddMethodMapping(ctx.RuneCount,
|
||||
nil,
|
||||
[][2]string{},
|
||||
)
|
||||
|
||||
ns.AddMethodMapping(ctx.CountWords,
|
||||
[]string{"countwords"},
|
||||
[][2]string{},
|
||||
|
@@ -57,6 +57,15 @@ func (ns *Namespace) CountRunes(s interface{}) (int, error) {
|
||||
return counter, nil
|
||||
}
|
||||
|
||||
// RuneCount returns the number of runes in s.
|
||||
func (ns *Namespace) RuneCount(s interface{}) (int, error) {
|
||||
ss, err := cast.ToStringE(s)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("Failed to convert content to string: %s", err)
|
||||
}
|
||||
return utf8.RuneCountInString(ss), nil
|
||||
}
|
||||
|
||||
// CountWords returns the approximate word count in s.
|
||||
func (ns *Namespace) CountWords(s interface{}) (int, error) {
|
||||
ss, err := cast.ToStringE(s)
|
||||
|
@@ -173,6 +173,33 @@ func TestCountRunes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuneCount(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for i, test := range []struct {
|
||||
s interface{}
|
||||
expect interface{}
|
||||
}{
|
||||
{"foo bar", 7},
|
||||
{"旁边", 2},
|
||||
{`<div class="test">旁边</div>`, 26},
|
||||
// errors
|
||||
{tstNoStringer{}, false},
|
||||
} {
|
||||
errMsg := fmt.Sprintf("[%d] %v", i, test.s)
|
||||
|
||||
result, err := ns.RuneCount(test.s)
|
||||
|
||||
if b, ok := test.expect.(bool); ok && !b {
|
||||
require.Error(t, err, errMsg)
|
||||
continue
|
||||
}
|
||||
|
||||
require.NoError(t, err, errMsg)
|
||||
assert.Equal(t, test.expect, result, errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCountWords(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
Reference in New Issue
Block a user