【问题标题】:issue with nested if? [duplicate]嵌套if的问题? [复制]
【发布时间】:2012-12-13 06:00:44
【问题描述】:

可能重复:
Django templates syntax error

当我在此代码上使用 {% if request.user.is_authenticated %} 条件进行重定向时,它会引发错误 Invalid block tag: 'else'

{% if request.user.is_authenticated %}

{% extends "pages/page.html" %}
{% load mezzanine_tags shop_tags i18n %}
{% block body_id %}category{% endblock %}
{% block main %}{{ block.super }}
{% regroup products by category as products_by_category %}
{% for c in products_by_category %}
......  
         {% for p in c.list %}     
......
        {% if p.num_in_stock == None %}
...
         {% else %}
         {% if p.num_in_stock < 4 %}
...
            {% endif %}
            {% endif %}
        .....        
                   {% endfor %}
......
{% endfor %}
{% endblock %}

{% else %}

<script>
window.location="/stylequiz/";
</script>

如果我使用这个脚本,那么它不会出错

{% if request.user.is_authenticated %}
   <h1>welcome</h1>
{% else %}

<script>
window.location="/stylequiz/";
</script>
{% endif %}

我觉得nested if肯定有问题。

【问题讨论】:

  • 当然一些对齐不会有伤害..
  • 你能详细说明你的评论吗..
  • 我认为他的意思是“你的 for/endfor、if/endif 块没有对齐,而且很难阅读。”

标签: python django templates if-statement nested-if


【解决方案1】:

您不能将{%extends%} 标签放在{%if%} 中。它应该是模板中的第一个标签。

来自 django 文档Template inheritance

如果您在模板中使用 {% extends %},它必须是该模板中的第一个模板标签。否则模板继承将不起作用。

【讨论】:

  • 但是如果我们把它放在 if 条件之外,那么它会打印出我们不想要的值
  • @user1896946,在这种情况下,您必须重新构建模板,这样您就不必将{%extends%} 放入{%if%}
猜你喜欢
  • 2015-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2018-09-17
  • 1970-01-01
  • 2022-07-07
相关资源
最近更新 更多