Django模板,发送两个参数到模板标签?

时间:2016-08-18 14:41:56

标签: python django templates

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

这个问题How do I add multiple arguments to my custom template filter in a django template?几乎就在那里,但我不知道如何将我的两个字段名称作为字符串发送。

我的模板:

    <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  

1 个答案:

答案 0 :(得分:6)

从我的角度来看,使用简单标签而不是模板过滤器看起来更容易,因此无需发送字符串即可调用它。

Thread Context

您的模板只是:

{% 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