django: how to do calculation inside the template html page?
For CSS like in your example you could use calc().
<img style="padding-top: calc({{ img.height }} / 2)" src=""/>
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()
@register.filter
def div( value, arg ):
'''
Divides the value; argument is the divisor.
Returns empty string on any error.
'''
try:
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 }}
There's a Python package that provides basic maths for Django templates: https://pypi.python.org/pypi/django-mathfilters
With this, you can do it:
{% load mathfilters %}
<img style="padding-top: {{ img.height|div:2 }}" src=""/>
Sometimes you just have to do it in the template. The following DjangoSnippet works great. Although you can abuse it, there are times when it Makes Life Simpler®.
ExprTag - Calculating python expression and saving the result to a variable
Note: Not tested in 1.3, but works fine with anything before that.