Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add template funcs countwords and countrunes #1440

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/content/templates/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,26 @@ Converts all characters in string to uppercase.
e.g. `{{upper "BatMan"}}` → "BATMAN"


### countwords

`countwords` tries to convert the passed content to a string and counts each word
in it. The template functions works similar to [.WordCount]({{< relref "templates/variables.md#page-variables" >}}).

```html
{{ "Hugo is a static site generator." | countwords }}
<!-- outputs a content length of 6 words. -->
```


### countrunes

Alternatively to counting all words , `countrunes` determines the number of runes in the content and excludes any whitespace. This can become useful if you have to deal with
CJK-like languages.

```html
{{ "Hello, 世界" | countrunes }}
<!-- outputs a content length of 8 runes. -->
```


## URLs
Expand Down
40 changes: 40 additions & 0 deletions tpl/template_funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"strconv"
"strings"
"time"
"unicode/utf8"

"github.com/spf13/cast"
"github.com/spf13/hugo/helpers"
Expand Down Expand Up @@ -1317,6 +1318,43 @@ func ModBool(a, b interface{}) (bool, error) {
return res == int64(0), nil
}

func CountWords(content interface{}) (int, error) {
conv, err := cast.ToStringE(content)

if err != nil {
return 0, errors.New("Failed to convert content to string: " + err.Error())
}

counter := 0
for _, word := range strings.Fields(helpers.StripHTML(conv)) {
runeCount := utf8.RuneCountInString(word)
if len(word) == runeCount {
counter++
} else {
counter += runeCount
}
}

return counter, nil
}

func CountRunes(content interface{}) (int, error) {
conv, err := cast.ToStringE(content)

if err != nil {
return 0, errors.New("Failed to convert content to string: " + err.Error())
}

counter := 0
for _, r := range helpers.StripHTML(conv) {
if !helpers.IsWhitespace(r) {
counter++
}
}

return counter, nil
}

func init() {
funcMap = template.FuncMap{
"urlize": helpers.URLize,
Expand Down Expand Up @@ -1371,6 +1409,8 @@ func init() {
"readDir": ReadDir,
"seq": helpers.Seq,
"getenv": func(varName string) string { return os.Getenv(varName) },
"countwords": CountWords,
"countrunes": CountRunes,
}

}