django:如何在模板 html 页面内进行计算? [英] django: how to do calculation inside the template html page?

查看:87
本文介绍了django:如何在模板 html 页面内进行计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用缩略图插件来获取图像的宽度和高度,现在我想使用从缩略图插件中获取的高度来定义 img 标签的填充,例如:

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

但是我这里出错了,django 不允许这样计算吗?

But I got error here, does django not allow calculate like this?

推荐答案

很遗憾没有.您需要使用过滤器,例如内置的 add 过滤器:

Unfortunately not. You need to use filters, like the add one which is built in:

{{ img.height|add:1 }}

div 不是,但是;不过,您可以自己实现:

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

用法类似,即:

{{ img.height|div:2 }}

这篇关于django:如何在模板 html 页面内进行计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆