【问题标题】:Django - Template with 'if x in list' not workingDjango - 带有“if x in list”的模板不起作用
【发布时间】:2012-12-29 00:11:25
【问题描述】:

我有一个看起来像这样的 Django 模板:

{% if thing in ['foo', 'bar'] %}
    Some HTML here
{% else %}
    Some other HTML
{% endif %}

问题是它空着回来。如果我切换到这个:

{% if thing == 'foo' or thing == 'bar' %}
    Some HTML here
{% else %}
    Some other HTML
{% endif %}

它工作正常。有什么原因你不能在 Django 模板中使用 x in list 吗?

【问题讨论】:

    标签: python django


    【解决方案1】:

    从视图中的上下文数据发送列表。

    Views.py:

    class MyAwesomeView(View):
        ...
        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            context['list'] = ('foo', 'bar')
            ...
            return context
    

    我的模板.html:

    {% if thing in list %}
        Some HTML here
    {% else %}
        Some other HTML
    {% endif %}
    

    在 Django 版本 3.2.3 上测试。

    【讨论】:

      【解决方案2】:

      this 答案的帮助下,我得到了它。我们可以使用split 在模板本身内部生成一个列表。我的最终代码如下(我想同时排除"user""id"

              {% with 'user id' as list %}
              {% for n, f, v in contract|get_fields %}
              {% if n not in list.split %}
              <tr>
                  <td>{{f}}</td>
                  <td>{{v}}</td>
              </tr>
              {% endif %}
              {% endfor %}
              {% endwith %}
      

      【讨论】:

        【解决方案3】:

        你可以。但是您不能在模板中使用列表文字。要么在视图中生成列表,要么避免使用if ... in ...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-06
          • 2020-07-12
          • 2020-08-09
          • 2019-07-03
          • 2018-02-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多