Django模板,向模板标签发送两个参数? [英] Django template, send two arguments to template tag?

查看:214
本文介绍了Django模板,向模板标签发送两个参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我是否可以将多个变量从字段名称发送到模板标记吗?

Can anyone tell me if its possible to send multiple variables from field names to a template tag?

这个问题如何在我的自定义模板过滤器中添加多个参数django模板?差不多在那里,但是我不知道如何将我的两个字段名作为字符串发送。

this question How do I add multiple arguments to my custom template filter in a django template? is almost there, but i dont know how to send my two field names as a string.

我的模板:

    <th>{{ item.cost_per_month|remaining_cost:item.install_date + ',' + item.contract_length }}</th>

以上操作无效

我的模板标签:

@register.filter('contract_remainder')
def contract_remainder(install_date, contract_term):
    months = 0
    now = datetime.now().date()
    end_date = install_date + relativedelta(years=contract_term)

    while True:
        mdays = monthrange(now.year, now.month)[1]
        now += timedelta(days=mdays)
        if now <= end_date:
            months += 1
        else:
            break
    return months    

@register.filter('remaining_cost')
def remaining_cost(cost_per_month, remainder_vars):
    dates = remainder_vars.split(',')
    cost = contract_remainder(dates[0], dates[1]) * cost_per_month
    return cost  


推荐答案

从我的角度来看,使用简单的标记而不是模板过滤器看起来更容易,因此您可以

From my point of view it looks easier to use a simple tag instead of a template filter so you can call it without needing to send a string.

https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#simple-tags

您的模板将是:

{% load remaining_cost %}
{# Don't forget to load the template tag as above #}

<th>{% remaining_cost item.cost_per_month item.install_date item.comtract_length %}</th>

,模板标记为:

@register.simple_tag
def remaining_cost(cost_per_month, install_date, contract_length):
    cost = contract_remainder(install_date, contract_length) * cost_per_month
    return cost 

这篇关于Django模板,向模板标签发送两个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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