dutchJSCOOP dutchJSCOOP - 1 year ago 95
HTML Question

Setting height of html img element with function

I'm trying to set the height of images loaded into my html file with Django as such:

<img data-original={{img.url}} width='310' height=calcHeight({{img.height}}, {{img.width}})/>

With the 'calcHeight(h,w)' function being a simple function to scale the height of the image in proportion to the width of 310. I have to do this because I use a lazyloader plugin that needs to generate empty placeholders for the images prior to loading the images themselves. The images are of varying dimensions so I need to get the height and the width of the images before the actual images are loaded, otherwise the placeholders will be of 'no height' prior to loading the actual images, causing the layout to get messed up in the process.

The code above doesn't work and I'm guessing it is because you can't call a function for height like that. I hope I explained the question precise enough and thanks in advance for any tips!

Answer Source

You can't call a function that takes arguments inside a Template with Django. In order to achieve that you'll need to write a template tag or filter yourself.

Then you'd be able to do something like:

{% my_img_tag img.url img.height img.width %}

Which would go in your tag constructor:

def my_img_tag(url, height, width):
    new_height = calcHeight(height, width)
    return {'url': url, 'height': new_height, 'width': width}

And you template could something like:

<img data-original="{{url}}" width="{{width}}" height="{{height}}"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download