【问题标题】:Using 'with' template tag in combination with 'if' template tag将“with”模板标签与“if”模板标签结合使用
【发布时间】:2018-05-20 09:21:13
【问题描述】:

在 Django 模板中我们可以使用with:

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

我们可以将withif 结合使用

我试过了:

{% with a={%if product.url %}product.url{%else%}default{%endif %} %}

但我得到一个错误:

Could not parse the remainder: '{%if' from '{%if'

【问题讨论】:

标签: django django-templates


【解决方案1】:

至少 Django 模板语言很傻——逻辑不应该发生在模板中——所以考虑一个模板标签 => 注册你自己的并尝试在视图中移动逻辑...

在这种情况下,问题可能是您为什么要这样做?

在需要的地方直接使用变量可能会更容易,如果它是 None 使用默认的模板标签/函数:

{{ product.url|default_if_none:default }}

但无论如何,您的解决方案可能如下所示:

{% with a=default %}
  {% if product.url %}
    {% update_variable product.url as a %}
  {% endif %}
{% endwith %}

你的模板标签应该是这样的:

@register.simple_tag
def update_variable(value):
    return value

【讨论】:

  • 我在数据库中有两个字段/列,如果一个字段为空,我从另一个字段获取值;因为是作为更复杂的查询集获得的(具有多个 prefetch_related)我不做视图中的逻辑
  • 嗯,好吧 - 比使用我发布的模板标签来做 - 无论如何都应该工作......
【解决方案2】:

一个可能起作用的标签过滤器:

from django import template

register = template.Library()

@register.simple_tag
def fallback(value, default_value):
     if not value:
         return default_value
     return value

在模板中,你需要加载文件

{% load app_containing_tag_filters %}

{% with a = product.url|fallback:default %}
     stuffs here
{% endwith %}

【讨论】:

    猜你喜欢
    • 2012-03-31
    • 2022-11-25
    • 2021-12-05
    • 2014-03-20
    • 2020-11-06
    • 2011-02-09
    • 2011-06-15
    • 1970-01-01
    • 2011-11-28
    相关资源
    最近更新 更多