django - 如何在 Django 模板上使用 if/else 条件?

标签 django templates django-templates

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

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

在 HTML 模板中,我想完成以下内容:

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

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

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

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

最佳答案

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

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

关于django - 如何在 Django 模板上使用 if/else 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11372177/

相关文章:

c++ - C++11 中使用模板参数的递归可变参数 void 函数

django - django 模板是如何解析的?

python - 如何在 Django 中调试失败的测试?

C++0x 将参数传递给可变参数模板函数

templates - CLI/C++接口(interface)类,通用方法调用模板方法

django - “str”对象没有属性 'relative_url'

python - Django - 保存并添加另一个功能

python - 本地化 Pandas 日期时间索引时出现 NonExistentTimeError

python - 如何在 Django REST 框架中返回自定义 JSON

python - 使用百分比计算 : decimal or readable?