Bin Chen Bin Chen - 10 months ago 41
Python Question

django: how to do caculation inside the template html page?

Hi I am using thumbnail plugin to get the image's width and height, now I want to define the padding of the img tag using the gotten height from thumbnail plugin, like:

<img style="padding-top: {{ img.height / 2 }}" src=""/>

But I got error here, does django not allow calculate like this?


Unfortunately not. You need to use filters, like the add one which is built in:

{{ img.height|add:1 }}

The div is not, however; you can implement it yourself, though:

from django import template
register = template.Library()

def div( value, arg ):
    Divides the value; argument is the divisor.
    Returns empty string on any error.
        value = int( value )
        arg = int( arg )
        if arg: return value / arg
    except: pass
    return ''

The usage would be similar, i.e.:

{{ img.height|div:2 }}