Invalid block tag on line 7: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?

Viewed 5325

I am beginner in html-templates and Django.

author_list.html

{% extends "base_generic.html" %}
{% block content %}
<h1>All authors</h1>
<ul>
    {% for author in author_list %}
    <li><a href="">{{ author.last_name }}:</a> {% for book in author.book_set.all %} {{ book.title }} {% if not
        forloop.last %}, {% endif %}{% endfor %}</li>
    {% endfor %}
</ul>
{% endblock %}

Error: Invalid block tag on line 7: 'endif', expected 'empty' or 'endfor'. Did you forget to register or load this tag?

I have the block of code. It works without block if, but doesn't work with the conditional. How to fix it. Help! I should paste "," after each name of book.

1 Answers

You should not write template tags on multiple lines. A template tag should start (with {%) and end (with %}) on the same line. Otherwise the Django template language parser will error on this. You thus should rewrite this to:

{% extends "base_generic.html" %}
{% block content %}
<h1>All authors</h1>
<ul>
    {% for author in author_list %}
    <!--                                                                                                 same line ↓ -->
    <li><a href="">{{ author.last_name }}:</a> {% for book in author.book_set.all %} {{ book.title }} {% if not forloop.last %}, {% endif %}{% endfor %}</li>
    {% endfor %}
</ul>
{% endblock %}
Related