Hugo

Get a set of integers from a string

I have a front-matter parameter, Params.img.ratio (indicating the image’s aspect ratio). I’m using forestry.io so the user chooses from a pre-defined list of options (5x4, 4x5, 16x9, and so on.). I need to break these numbers out into separate integers, in order to perform some math functions on them. (Please note that these images are hosted remotely and therefore imageConfig is not available to me.) The following (verbose, probably very misguided) code does yield the separate numbers, but as strings—not integers:

{{- $arWidth := index (first 1 (split .Params.img.ratio "x") ) 0 -}}
(For a 16x9 aspect ratio, this yields the string 16.)

{{- $arHeight := index (last 1 (split .Params.img.ratio "x") ) 0 -}}
(For a 16x9 aspect ratio, this yields the string 9.)

If, however, i attempt the following:

{{- $arWidth :=  int ( index (first 1 (split .Params.img.ratio "x") ) 0 ) -}}
{{- $arHeight := int ( index (last 1 (split .Params.img.ratio "x") ) 0 ) -}}

I receive the following error:

error calling int: unable to cast "" of type string to int

If anyone can see through this mess of code, and identify a better way, i’ll be in your debt.

This works for me locally:

{{ $ratio := "16x9" }}
{{ $split := split $ratio "x" }}
{{ $width := int (index $split 0) }}
{{ $height := int (index $split 1) }}

{{ add $width $height }} // equals 25, to prove that they are indeed ints
1 Like

Thank you for your reply, @zwbetz! Your code does work as designed in my partial.

I’m stumped though, because as soon as i make the following change:

{{ $ratio := .Params.img.ratio }}
{{ $split := split $ratio "x" }}
{{ $width := int (index $split 0) }}
{{ $height := int (index $split 1) }}

i get the same error:

at <int (index $split 0)>: error calling int: unable to cast "" of type string to int

I can confirm that {{ printf "%#v" .Params.img.ratio }} yields "16x9".

If i do the following:

{{ $ratio := .Params.img.ratio }}
{{ $split := split $ratio “x” }}
{{ printf “%#v” $split }}

it yields: []string{""}

It seems to be trying to cast an empty string ("") as an integer, when the param is definitely not empty…

Maybe some of your pages have a value for that param. And some don’t. So add some logic beforehand that checks if that param is nil or empty string.

2 Likes

Dang @zwbetz, how many times can you come to my rescue? Appreciate you so much!

1 Like