Unexpected issue with humanize and whitespace

Just thought worth logging this here in case anyone else runs into the same issue (it took us a little time to track down the cause). We have some data fields we publish using Hugo coming from another system, and sometimes those fields contain messy data. We discovered that a field we are calling humanize on like so:

{{ if ne .part "" }}
  <li> {{ humanize .part }} </li>

was breaking with the error:

execute of template failed: template: partials/details.html:115:22: executing “partials/details.html” at <humanize .part>: error calling humanize: runtime error: index out of range [0] with length 0

which turned out to be because the field just contained a single whitespace. A bit of testing showed that calling humanize on a field containing whitespace only always breaks, presumably because the underlying library (flect) is splitting the string on whitespace and expecting an array it can access.

Of course an easy fix is to call trim on the field first before testing/calling humanize. Was just a little surprised it had this impact.

1 Like

Just another option:

instead of using an additional call on trim the condition could be written using: strings.ContainsNonSpace | Hugo which return false for empty strings and strings containing only whitespace, too

{{ if strings.ContainsNonSpace .part }}

https://github.com/gohugoio/hugo/issues/12827

1 Like

Thanks both, I wasn’t sure if it was fair enough to say it was a bug, as it might be expected for us to check the string content before passing to humanize, but it was unexpected to get a runtime error.