Django模板如果有列表

pra*_*432 1 django list django-templates

我有一个Django模板,我认为我的if语句有一些语法错误.`

<head>
<link rel="stylesheet" type="text/css" href="/static/css/styles.css" /> 
<Meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h1>Testing the class page</h1>

<div id = "bookResults">
<ul>
{% if books %}
    {% for book in books %}
        <li>
            <div class="bookDisplay">
                <div>
                    <text class= "text" id = "bookTitle">{{ book.title|safe }}</text><br/>
                    <text class= "text" id= "bookAuthor">by {{ book.author|safe }}</text><br/>
                    <text class = "test" id = "bookDetails">
                        ISBN: {{ book.isbn|safe }}
                        Bookstore Price: {{ book.price }}

                    </text><br/>
                    <img src= "{{ book.imageURL }}" class = "bookImage" />
                </div>
            </div>
        </li>   
    {% endfor %}
{% else %}
    <h2>Sorry, no books or classes were found- can you try searching again?"</h2>
{% endif %}
</ul>
</div>

</body> 

</html>`
Run Code Online (Sandbox Code Playgroud)

我基本上试图说 - 如果书籍(列表)有价值然后做下面的一切,如果没有,做其他事情 - 我已经尝试{{if books | length> 0}}但是没有果

如果工作,我该怎么做?

谢谢

Cat*_*lus 8

这段代码没有错.你也可以像这样写:

<ul>
{% for book in books %}
    <li>...</li>
{% empty %}
    <h2>Sorry, no books</h2>
{% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)

如果它无法正常工作,那么您将错误的上下文传递给模板.