Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Add template funcs countwords and countrunes
  • Loading branch information
digitalcraftsman committed Sep 20, 2015
commit f4f46a7edeb3631de42c519d6876c867a79ee1dd
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,
}

}