【问题标题】:How to use if/else condition on Django Templates?如何在 Django 模板上使用 if/else 条件?
【发布时间】:2012-07-07 12:01:51
【问题描述】:

我将以下字典传递给渲染函数,源是字符串列表,标题是可能等于源中的字符串之一的字符串:

{'title':title, 'sources':sources})

在 HTML 模板中,我想在以下几行中完成一些事情:

{% for source in sources %}
  <tr>
    <td>{{ source }}</td>
    <td>
      {% if title == {{ source }} %}
        Just now!
      {% endif %}
    </td>
  </tr>
{% endfor %}

但是,以下文本块会导致错误:

TemplateSyntaxError at /admin/start/
Could not parse the remainder: '{{' from '{{'

...{% if title == {{ source }} %} 以红色突出显示。

【问题讨论】:

    标签: django templates django-templates


    【解决方案1】:

    很抱歉在旧帖子中发表评论,但如果您想使用 else if 语句,这将对您有所帮助

    {% if title == source %}
        Do This
    {% elif title == value %}
        Do This
    {% else %}
        Do This
    {% endif %}
    

    欲了解更多信息,请参阅https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#if

    【讨论】:

    • 链接已损坏。请问可以修吗?
    【解决方案2】:

    试试这个。

    我已经在我的 django 模板中尝试过了。

    它会正常工作的。只需从 {{source}} 中删除花括号对 {{}}

    我还添加了

    标签和 就是这样

    修改后,您的 代码 将如下所示。

    {% for source in sources %}
       <table>
          <tr>
              <td>{{ source }}</td>
              <td>
                  {% if title == source %}
                    Just now! 
                  {% endif %}
              </td>
          </tr>
       </table>
    {% endfor %}
    

    我的字典如下所示,

    {'title':"Rishikesh", 'sources':["Hemkesh", "Malinikesh", "Rishikesh", "Sandeep", "Darshan", "Veeru", "Shwetabh"]}
    

    OUTPUT 在我的 模板 被渲染后如下所示。

    Hemkesh 
    Malinikesh  
    Rishikesh   Just now!
    Sandeep 
    Darshan 
    Veeru   
    Shwetabh    
    

    【讨论】:

      【解决方案3】:

      您不应该在ififequal 语句中使用双括号{{ }} 语法,您可以像在普通python 中一样简单地访问那里的变量:

      {% if title == source %}
         ...
      {% endif %}
      

      【讨论】:

      • 这是因为if 还是ifequal?还是因为{% %}括号?
      • 同样的问题:这是针对iffor 的吗?还是因为{% %}括号?
      • 这是因为{% %} 括号。请参阅此内容和 {{ }},作为对 HTML 的转义,允许您使用类似 python 的语法并访问通过模板上下文发送的任何变量。
      【解决方案4】:
      {% for source in sources %}
        <tr>
          <td>{{ source }}</td>
          <td>
            {% ifequal title source %}
              Just now!
            {% endifequal %}
          </td>
        </tr>
      {% endfor %}
      
                      or
      
      
      {% for source in sources %}
            <tr>
              <td>{{ source }}</td>
              <td>
                {% if title == source %}
                  Just now!
                {% endif %}
              </td>
            </tr>
          {% endfor %}
      

      See Django Doc

      【讨论】:

      • 现在已弃用
      猜你喜欢
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 2022-01-25
      • 2017-08-14
      • 2015-04-24
      • 1970-01-01
      相关资源
      最近更新 更多