【问题标题】:How to save the result of a comparison using Django's 'with' template tag?如何使用 Django 的“with”模板标签保存比较结果?
【发布时间】:2015-06-19 08:43:53
【问题描述】:

我想在 django 模板中创建一个新的变量,它会有一个比较的值

obj.site.profile.default_role == obj

不幸的是,这些代码都不起作用:

{% with obj.site.profile.default_role==obj as default %}{% endwith %}

{% with default=obj.site.profile.default_role==obj %}{% endwith %}

正确的语法是什么?

【问题讨论】:

  • 你不只是想做:{% with default=obj.site.profile.default_role %}吗?您为什么要尝试将其与对象本身进行比较?它永远不会相等。
  • ... 我向你保证,我现在需要什么 ;) 但为了争论,让我们假设,我要{% with x==y as boolean_variable %}
  • 为什么不在视图中进行比较,然后将boolean_variable发送到视图?
  • @Gocht:我可以做到,但我想知道解决方案(如果存在的话),而不是解决方法;)
  • with 将一个或多个值添加到上下文以进行缓存和轻松访问。 它尚未准备好评估表达式。正如@Gocht 解释的那样,您应该在视图中而不是在模板中烹饪值。在视图上烹饪值不是一种解决方法;)查看源代码:github.com/django/django/blob/…

标签: python django django-templates


【解决方案1】:

with 可以只接受一个“普通”上下文变量。

您可以尝试assignment-tags,将您的参数传递给它。

@register.assignment_tag
def boolean_tag(default_role, obj):
    return default_role == obj

在模板中

{% boolean_tag obj.site.profile.default_role obj as my_check %}

如果在一个模板块中使用变量(如您的情况,当您尝试使用with 时),则此解决方案很好。如果您需要在多个页面块中使用变量,将其添加到带有include 标签的页面上下文会更好

【讨论】:

【解决方案2】:

with 标签不支持值评估。

我可以想象的唯一可能的纯模板解决方案是将部分html拆分为子模板并使用{% include %}标签

{% if obj.site.profile.default_role==obj %}
    {% include 'subtemplate.html' with default=True %}
{% else %}
    {% include 'subtemplate.html' with default=False %}
{% endif %} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2021-12-05
    • 2019-12-01
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多