Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: how to do calculation 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?

like image 913
Bin Chen Avatar asked May 01 '11 14:05

Bin Chen


People also ask

How do I declare a variable inside a Django template?

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.

How do you use arithmetic operations in Django template?

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.

How do you pass variables from Django view to a template?

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.


2 Answers

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 }}
like image 113
Xion Avatar answered Oct 08 '22 00:10

Xion


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=""/>
like image 37
Wilfred Hughes Avatar answered Oct 08 '22 00:10

Wilfred Hughes