【问题标题】:Django - string from variable inside template tagDjango - 来自模板标签内变量的字符串
【发布时间】:2017-03-19 08:43:28
【问题描述】:

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

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

自定义模板过滤器

@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 %}

但这引发了:

异常值:int() 以 10 为底的无效文字:'{{ day }}'

你有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    当您在{% %} 中时,您不需要{{}}。只需直接在该标记中使用名称并使用字符串 concat 模板语法 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 %}
    

    【讨论】:

    • 不幸的是,这不起作用。我不确定为什么。可能,天和小时是整数。它返回:异常值:'int'对象没有属性'split',如果我打印dayhour变量,它会打印0而不是“0,2”。
    • 似乎是一个不错的方法,但存在一些问题,可能与语法有关。 u'with' 收到了一个无效的令牌:u'hour|stringformat:"s"' 我试图找出错误的意义所在。
    • 好的,我在上面添加了字符串格式( {% with day=forloop.counter|add:"-2"|stringformat:"s" hour=forloop.parentloop.counter| add:"-2"|stringformat:"s" hours_yesterday=forloop.counter|add:"-2"|days_to_hours %} )并且它有效。谢谢
    猜你喜欢
    • 2011-08-27
    • 1970-01-01
    • 2014-01-04
    • 2015-11-25
    • 2015-02-26
    • 2014-03-04
    • 1970-01-01
    • 2017-07-12
    • 2013-09-02
    相关资源
    最近更新 更多