处理我们正在使用django模板的遗留项目。 如何将这个/ if语法从Jinja2转换为django:
这个Jinja示例按预期工作,但在django中出现语法错误:
{% for story in stories if story.status == "draft" %}
<h1> {{story.title}} </h1>
{% empty %}
<p> No drafts to see here</p>
{% endfor %}
{% for story in stories if story.status == "published" %}
<h1> {{story.title}} </h1>
{% empty %}
<p> No published stories to see here</p>
{% endfor %}
这不适用于{% empty %}
因为if语句在里面
for循环的范围。
{% for story in stories %}
{% if story.status == "draft" %}
<h1> {{story.title}} </h1>
{% endif %}
{% empty %}
<p> No drafts to see here</p>
{% endfor %}
{% for story in stories %}
{% if story.status == "published" %}
<h1> {{story.title}} </h1>
{% endif %}
{% empty %}
<p>No published stories</p>
{% endfor %}
答案 0 :(得分:1)
django模板系统有一些文档:
https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#if
这应该做:
{% if stories|length %}
{% for story in stories %}
{% if story.status == "published" %}
<h1> {{story.title}} </h1>
{% endif %}
{% endfor %}
{% else %}
<p>Nothing to see here.</p>
{% endif %}