praks5432
praks5432

Reputation: 7792

Django Template if with list

I have a Django template and I think there's some syntax error here with my if statement. `

<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>`

I'm basically trying to say- if books (which is a list) has a value then do everything below it, if not, do something else - I've already tried {{ if books|length > 0 }} but to no avail

what should I do to get this if working?

Thanks

Upvotes: 1

Views: 2804

Answers (1)

Cat Plus Plus
Cat Plus Plus

Reputation: 130004

There is nothing wrong with this code. You can also write it like this:

<ul>
{% for book in books %}
    <li>...</li>
{% empty %}
    <h2>Sorry, no books</h2>
{% endfor %}
</ul>

If it doesn't work properly, then you're passing wrong context to the template.

Upvotes: 8

Related Questions