[SOLVED] Trigger floating values with imageConfig?

I am trying to calculate with Hugo’s math functions the padding ratio for images that I lazy load.

And I have pretty much ran into the issue in this thread where @tatsushid wrote:

Here is what I tried and of course this returns an integer (that is unusable to set the correct padding):
First set some variables:

{{ $src := .Get “src” }}
{{ $config := imageConfig (printf “/static/%s” $src) }}

And then do the math:

style=“padding-bottom:{{mul (div $config.Height $config.Width) 100}}%;”

I cannot get the padding ratio because the division of image height ÷ width returns an integer that is usually 1, when the actual value is something like 1.3401.

I tried appending a .0 after the $config.Height variable but of course this throws an error.

Is it possible to trigger the doArithmetic conversion to float in this case?

I guess that it is not possible to do this with Hugo Math Functions.

However I just managed to do what I needed with CSS inside my img shortcode.

Like this:

<div class="magnifik" style="padding-bottom:calc( {{$config.Height}} / {{$config.Width}} * 100%);"}>

I had to waste my time for this today, because Firefox 54 does not seem to keep the reserved space for an image even though the height and width attributes are set… And the layout was a pure mess while the page was loading…

I didn’t have this problem in Chrome and Safari (both on desktop and mobile). WebKit respects the space reserved for an image (like it should).

Haven’t tested Edge or IE 11 (and TBH I don’t want to)…


I’m not at my work desk so cannot test, but how about something like this?

{{ $height := mul $confg.Height 1.0 }}

style=“padding-bottom:{{mul (div $height $config.Width) 100}}%;

The attempt with this intermediate height variable is to get a float variable with the image height, instead of having to use the integer variable with the division operation.

Might not work but just an idea. :slight_smile:


@Jura Thank you so much! :clap:

That works perfectly!