我正在尝试根据类别ID为不同的类别添加不同的模板。我正在使用Django 1.3。 Switch案例不适用于Django 1.3,我收到此错误:
Invalid block tag: 'switch', expected 'endblock' or 'endblock content'
但是开关盒已正确关闭。
这是我的代码:
{% switch property.category.id %}
{% case 0 %}
<h4>'agriculture'</h4>
{% case 1 %}
<h4>'Residential'</h4>
{% case 2 %}
<h4>'commiercial'</h4>
{% case 3 %}
<h4>'mixed use'</h4>
{% case 4 %}
<h4>'Industrial'</h4>
{% else %}
<h4>'retail'</h4>
{% endswitch %}
此代码中的错误是什么?
答案 0 :(得分:2)
There is no {% switch %}
tag in Django template language. To solve your problem you can
{% if %}
s. The second option in code:
{% if property.category.id == 0 %}
<h4>'agriculture'</h4>
{% elif property.category.id == 1 %}
<h4>'Residential'</h4>
{% elif property.category.id == 2 %}
<h4>'commiercial'</h4>
{% elif property.category.id == 3 %}
<h4>'mixed use'</h4>
{% elif property.category.id == 4 %}
<h4>'Industrial'</h4>
{% else %}
<h4>'retail'</h4>
{% endif %}
As Alasdair correctly mentioned in his comment, the {% elif %}
tag was introduced in Django 1.4. To use the above code in an older version you need to upgrade your Django version or you can use a modified version:
{% if property.category.id == 0 %}
<h4>'agriculture'</h4>
{% endif %}
{% if property.category.id == 1 %}
<h4>'Residential'</h4>
{% endif %}
{% if property.category.id == 2 %}
<h4>'commiercial'</h4>
{% endif %}
{% if property.category.id == 3 %}
<h4>'mixed use'</h4>
{% endif %}
{% if property.category.id == 4 %}
<h4>'Industrial'</h4>
{% endif %}
{% if property.category.id < 0 or property.category.id > 4 %}
<h4>'retail'</h4>
{% endif %}
This modification is safe** (but inefficient) here since the ID can't be equal to two different integers at the same time.
** as long as you only use integers for the IDs which is probable
However I would strongly recommend upgrading to a newer Django version. Not only because of the missing {% elif %}
tag but mainly for security reasons.