Bin Chen
Bin Chen

Reputation: 63369

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?

Upvotes: 21

Views: 45650

Answers (4)

Scoop561
Scoop561

Reputation: 73

For CSS like in your example you could use calc().

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

Upvotes: 5

Xion
Xion

Reputation: 22780

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 }}

Upvotes: 43

Wilfred Hughes
Wilfred Hughes

Reputation: 31191

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=""/>

Upvotes: 10

Peter Rowell
Peter Rowell

Reputation: 17713

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.

Upvotes: 3

Related Questions