Django - {%if%}块中的模板标记

Ran*_* Ma 32 django templates django-templates

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

{'title':title, 'sources':sources})
Run Code Online (Sandbox Code Playgroud)

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

{% for source in sources %}
  <tr>
    <td>{{ source }}</td>
    <td>
      {% if title == {{ source }} %}
        Just now!
      {% endif %}
    </td>
  </tr>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

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

TemplateSyntaxError at /admin/start/
Could not parse the remainder: '{{' from '{{'
Run Code Online (Sandbox Code Playgroud)

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

Her*_*aaf 55

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

{% if title == source %}
   ...
{% endif %}
Run Code Online (Sandbox Code Playgroud)


Ant*_*ntu 19

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

{% if title == source %}
    Do This
{% elif title == value %}
    Do This
{% else %}
    Do This
{% endif %}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅Django 文档


shi*_*iva 9

{% 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 %}
Run Code Online (Sandbox Code Playgroud)

见Django Doc

  • 现在已弃用 (2认同)