【问题标题】:Django template, send two arguments to template tag?Django模板,向模板标签发送两个参数?
【发布时间】:2016-12-25 13:25:19
【问题描述】:

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

这个问题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  

【问题讨论】:

    标签: python django templates


    【解决方案1】:

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

    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 
    

    【讨论】:

    • 不知道简单标签!但是,当我使用简单标签时出现错误...“第 206 行上的块标签无效:'remaining_cost',预期为'elif','else'或'endif'。您是否忘记注册或加载此标签?206 {% remaining_cost item.cost_per_month item.install_date item.comtract_length %}
    • 对不起,我忘了。你必须把 {% load %}
    • 模板顶部
    • 嗨,是的,已经添加了,我在同一个 .py 上加载了一些其他过滤器
    • 我无法指出问题所在。您能否更新您的问题中的代码,以便我可以看到它现在的样子?
    猜你喜欢
    • 1970-01-01
    • 2018-10-21
    • 2011-02-09
    • 2014-02-26
    • 1970-01-01
    • 2012-02-01
    • 2021-02-18
    • 1970-01-01
    • 2014-03-20
    相关资源
    最近更新 更多