python - Django - 来自模板标签内变量的字符串

标签 python django django-templates django-template-filters

我不知道如何将多个参数发送到自定义模板过滤器。

问题是我使用模板变量作为参数。

自定义模板过滤器

@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

如果 dayhour 是字符串,则在连接字符串之前需要将类型转换为字符串:

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

相关文章:

python - 空数据错误 : No columns to parse from file about streamlit

python - 如何覆盖当前时间?

python - 通过 python 的多处理模块 : surely I've done something wrong 进行明显的时间旅行

python - 使用 Pandas Multiindex 处理数量失败并显示 'Categorical levels must be unique'

Django:模型字段的元组/固定大小列表

python - 使用 args 的 get_absolute_url() 的 Django 模板不起作用

django - 如何让 {% url logout %} 在我的 Django 模板中工作?

python - 正则表达式匹配以 _F<XX>_C<XX> 结尾的 URL

django - 具有基于类的 View 的多个表单。如何在同一页面显示错误?

python - 无法从父目录扩展 base.html