I got into an issue with the int function.
I used this int to remove the leading 0 from a date in string format and it works perfectly for all numbers except for 08 and 09.
the code is {{ int "09" }} and it throws this error:
ERROR 2017/08/10 14:32:19 Error while rendering "page": template: /path/list.html:15:11: executing "main" at <int "08">: error calling int: unable to cast "08" of type string to int
I don’t know if this is a bug or if I was lucky to get it work from 1 to 7, but if it isn’t is there another, and safer, way to remove a leading 0 in hugo?
It seems ‘int’ treats the number as octal, so you only get 0…7 symbols. There must be a way to tell int to treat the number as a decimal, but I can’t info on that.
We need to add the strings.TrimLeft func to our templates, but if you know that there will only be a single leading zero, you can use strings.TrimPrefix. And I just realized that we haven’t documented TrimPrefix or TrimSuffix.
So, here’s what I’d do to solve your problem:
{{ $day := int strings.TrimPrefix "0" (index $date 2) }}
thank you @moorereason!
it works, but your example got me first with an error for the int function (3 args instead of 1), and solved it with parentesis.
then I got only zeroes, so I figured out there was an error in the order of the args.
the final working code is this:
{{ $day := int (strings.TrimPrefix (index $date 2) "0") }}
thank you very much, I would have hated to leave the hardcoded condition on the code.
@yesh, I got those parameters backwards on TrimPrefix because I implemented it backwards! Doh!
We generally put the target variable as the last input so that you can use pipes, {{ $num | strings.TrimPrefix "0" }}. Since we haven’t published TrimPrefix and TrimSuffix in the docs yet, I’ll fix the function soon, so expect this section of your code to break when we push out the next release.
Generally, yes, but usually not enough to matter compared to the rest of the site build process. For instance, I build an alphabetical index of paginated recipes using: