python - Django 模板,向模板标签发送两个参数?

标签 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  

最佳答案

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

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 

关于python - Django 模板,向模板标签发送两个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39021159/

相关文章:

python - 如何防止 Django 模板中的自动转义?

javascript - 自定义组件 - 如何克隆定义为 js 字符串文字的 html 模板?

python - 如何从框架中清除 Django 登录消息

python - 如何使 Glom 与类似 dict 的对象一起工作

python - 迭代由其他类组成的类

python - .pxd 文件出现未知文件类型错误

python - Django - get_by_natural_key() 恰好接受 3 个参数(给定 2 个)

javascript - 当我在子页面时没有激活导航父页面

c++ - 模板函数的包装器

python - Pandas - 处理空单元格