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?
Another approach to declare variables in the template is by using custom template tags. Create a custom template tag files named as custom_template_tags.py . Paste the below code in it. Now inside the HTML template use this custom template tag setvar to define a new variable.
Use django-mathfilters. In addition to the built-in add filter, it provides filters to subtract, multiply, divide, and take the absolute value. For the specific example above, you would use {{ 100|sub:object.
And this is rather simple, because Django has built-in template modules that makes a transfer easy. Basically you just take the variable from views.py and enclose it within curly braces {{ }} in the template file. We won't go into a database example for this one.
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=""/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With