Lak*_*har 6 python django django-templates
我必须在 django 模板中减去两个值。我怎样才能做到这一点 ?
{{ obj.loan_amount }} - {{ obj.service_charge }}
Run Code Online (Sandbox Code Playgroud)
有两种方法可以做到这一点。
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})
Run Code Online (Sandbox Code Playgroud)
{{ obj_difference }}这将允许您在模板中直接使用。
2) 第二种方法不太理想,是使用模板标签。
@register.simple_tag(takes_context=True)
def subtractify(context, obj):
newval = obj.loan_amount - obj.service_charge
return newval
Run Code Online (Sandbox Code Playgroud)
{% subtractify obj %}这将允许您在模板中使用。
{% load [tagname] %}注意:如果您使用方法 #2,请不要忘记在 HTML 文件的顶部使用。
| 归档时间: |
|
| 查看次数: |
8742 次 |
| 最近记录: |