我不知道如何将多个参数发送到自定义模板过滤器。
问题是我使用模板变量作为参数。
自定义模板过滤器
@register.filter
def is_scheduled(product_id,dayhour):
day,hour = dayhour.split(',')
return Product.objects.get(id=product_id).is_scheduled(day,hour)
正常使用
{% if product.id|is_scheduled:"7,22" %}...{% endif %}
上面的行将正常工作,就像我将两个参数 - 7 和 22 放入过滤器(已测试 - 有效)一样。问题是我想将变量而不是纯文本/字符串作为参数。
在我的模板中:
{% with day=forloop.counter|add:"-2" hour=forloop.parentloop.counter|add:"-2" %}
现在,我想使用 {{ day }}
和 {{ hour }}
作为参数。
我试过例如:
{% if product.id|is_scheduled:"{{ day }},{{ hour }}" %}...{% endif %}
但这引发了:
Exception Value: invalid literal for int() with base 10: '{{ day }}'
你有什么想法吗?
最佳答案
当您位于 {% %}
内时,您不需要 {{}}
。只需在该标记中直接使用名称并使用字符串连接模板语法 add
。
如果 day
和 hour
是字符串,则在连接字符串之前需要将类型转换为字符串:
{% with day|stringformat:"s" as sday hour|stringformat:"s" as shour %}
{% with sday|add:","|add:shour as arg %}
{% if product.id|is_scheduled:arg %}...{% endif %}
{% endwith %}
{% endwith %}
关于python - Django - 来自模板标签内变量的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40440902/