【问题标题】:Django template passing a template variable into cut filterDjango模板将模板变量传递给剪切过滤器
【发布时间】:2012-04-05 03:13:26
【问题描述】:

我正在尝试将模板传递给剪切过滤器,类似于这样

{{ myVariable|cut:"something + templateVariable" }}

我试过了:

{{ myVariable|cut:"something"|add:templateVariable }}

{{ myVariable|cut:"something {{ templateVariable }}" }}

但这些不起作用。

这可能吗?

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    它应该与使用 with tag 的临时变量一起工作:

    {% with myFilter="something"|add:templateVariable %}
        {{ myVariable|cut:myFilter }}
    {% endwith %}
    

    或在 Django 1.2 及更早版本中:

    {% with "something"|add:templateVariable as myFilter %}
        {{ myVariable|cut:myFilter }}
    {% endwith %}
    

    Add 不支持字符串和 int 的连接,但您可以轻松地制作一个转换为字符串的 template filter,例如:

    from django import template
    
    register = template.Library()
    
    @register.filter
    def to_unicode(mixed):
        return unicode(mixed)
    

    将允许这样的模板标记表达式some_int|to_unicode|add:'foo'

    【讨论】:

    • 我发现它不起作用,因为您不能使用add 过滤器将字符串与整数变量连接起来。我只是创建了一个客户模板标签来处理它,并使用您编写的代码使事情变得更简单
    猜你喜欢
    • 2019-04-03
    • 2010-10-28
    • 2013-02-09
    • 1970-01-01
    • 2011-07-10
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 2017-11-10
    相关资源
    最近更新 更多