开发者

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?


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


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

<img style="padding-top: calc({{ img.height }} / 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜