Go to a Django project and write this line in a template
<!-- {% if context %} -->
What happens is that Django will raise this error:
TemplateSyntaxError: Unclosed tag on line XXX: 'if'. Looking for one of: elif, else, endif.
Wait, what? Why is a comment raising an error? Aren't comments ignored? Well... yes and no.*
Why is this happening?
The Django template engine parses everything, including content inside HTML comments (). So html comments aren't ignored (the no part).*
When it encounters {% if context %}
, even if it's inside an html comment, it expects a matching {% endif %}
. Since the endif
is missing, an error is raised.
Django treats HTML comments <!-- ... -->
as text, not as special syntax.
HTML comments are meant to be passed to the browser, although they are not displayed. Django processes their content because it doesn’t know you intend them to be ignored. Try it, make an html comment and then check the page source, html comments are there.
If you close the tag, no error happens.
<!-- {% if context %} {% endif %} -->
Use Django's Template comments and not html's. Django template's comments are ignored and aren't passed to the browser (the yes part).*
You have two options:
{# {% if context %} #}
{% comment %} {% if context %} {% endcomment %}