无效的块标记:django模板中的'else',预期'empty'或'endfor'

时间:2013-08-12 13:15:30

标签: django templates

我有一个模板,它有两个模板变量list_of_books, search_results

首先我检查是否存在任何一个变量的结果,如果不存在,则应显示Books not available如下所示

接下来,如果search_results变量有结果,我们应该循环并打印数据, 否则,如果list_of_books变量有结果,我们应该循环并打印数据

{% if list_of_books or search_results %}
   <table border="0" align="left" width="70%"> 
    {% if search_results %}
        {% for book in search_results %}
    {% else %}    
        {% for book in list_of_books %}
    {% endif %}    
      <tr>
        <td>  
            <a href="{{ book.get_absolute_url }}">{{ book.title }}</a>
        </td>
          </tr>
            {% endfor %}
    </table>

{% else %}
    <p>No Books available.</p>
{% endif %}

但是通过上面的html代码,我得到了以下错误,实际上我在编写模板标签时犯了错误?

Error during template rendering

In template /home/virtualenvironment/apps/books/templates/books/list_of_books.html, error at line 23
Invalid block tag: 'else', expected 'empty' or 'endfor'
20  <table border="0" align="left" width="70%">
21  {% if search_results %}
22  {% for book in search_results %}
23  {% else %}
24  {% for book in list_of_books %}
25  {% endif %}
26  <tr>
27  <td>
28  <a href="{{ book.get_absolute_url }}">{{ book.title }}</a>
29  </td>
30  </tr>
31  {% endfor %}
32  </table>

2 个答案:

答案 0 :(得分:1)

解决此问题的最佳方法可能是确保使用该模板的视图只使用相同的变量名。

如果那是不可能的话,我会这样做:

{% if list_of_books or search_results %}
    <table border="0" align="left" width="70%"> 
    {% if search_results %}
        {% include "book_listing.html" with books=search_results %}
    {% else %}    
        {% include "book_listing.html" with books=list_of_books %}
    {% endif %}
    </table>
{% else %}
    <p>No Books available.</p>
{% endif %}

然后将其放入book_listing.html

{% for book in books %}
  <tr>
    <td>  
      <a href="{{ book.get_absolute_url }}">{{ book.title }}</a>
    </td>
  </tr>
{% endfor %}

答案 1 :(得分:0)

<span>
    {%if booking.DiscountedFare == booking.TotalFare %}
        Rs.{{ booking.TotalFare }}

    {% else %}   
        Rs.{{ booking.DiscountedFare }}         

    {% endif %}
</span>