在django模板中减去两个变量

Subtracting two variables in django template

我必须在 Django 模板中减去两个值。我该怎么做?

{{ obj.loan_amount }} - {{ obj.service_charge }}

有两种方法可以做到这一点。

1) 更优选的方法(基于业务逻辑和模板逻辑的分离)是计算您在 views.py 中尝试执行的操作,然后通过上下文传递值。例如:

class FooView(View):
    def get(self, request, *args, **kwargs):
        obj = Foo.objects.get(pk=1)
        obj_difference = obj.loan_amount - obj.service_charge
        return render(request, 'index.html', {'obj': obj,
                                              'obj_difference': obj_difference})

这将允许您在模板中直接使用 {{ obj_difference }}

2) 第二种不太理想的方法是使用模板标签。

@register.simple_tag(takes_context=True)
def subtractify(context, obj):
    newval = obj.loan_amount - obj.service_charge
    return newval

这将允许您在模板中使用 {% subtractify obj %}

注意:如果您使用方法 #2,请不要忘记在 HTML 文件的顶部使用 {% load [tagname] %}