How to put comments in Django templates?
In Django templates, {% comment %} ... {% endcomment %}
is used for multi-line comments while {# comment #}
is used for single-line comments:
Note that {% comment %}
blocks do not render Na'Vi messages (AKA the HTML within) and {# ... #}
is like a stealthy agent, perfect for quick intelligence (AKA brief notes).
Proper syntax and common pitfalls
Django provides syntax for commenting exclusively to prevent templating mishaps. Here's some advice to help avoid common pitfalls:
- Avoid using HTML comment syntax (
<!-- comment -->
) as these become visible in the page's source code. Sneaky, but not sneaky enough! - Syntax
{% # comment %}
instead of{# comment #}
for single-line comments, is like ordering a pizza at a burger joint - you'll get an "Invalid template" error. - Hoping that
{# % %}
serves as a correct syntax for comments is like hoping for a unicorn to deliver your mail. Django only recognizes{# ... #}
for single-line comments. - Forgetting to close a comment block with
{% endcomment %}
is like leaving your house without pants, everything that follows could be potentially embarrassing as it gets ignored.
When to use comments?
Some might say "use comments all the time!", but comments are like salt—necessary but not in every dish and certainly not in excess. Here are cases where it's healthy to employ comments:
- Explaining complexity of template logic or whys of certain filters
- Providing context or instructions for other developers
- Outlining the purpose of a particular code block
- Disabling code for increments during debugging (Make sure to remove after, else it's like leaving wrenches in the engine!)
Commenting out for debugging
For the sherlocks out there, commenting can help isolate elusive issues:
Adding a brief dispatch within {% comment %}
signals why the code is in sleuth mode (commented out). It's like a secret debug handshake for the fellow developers.
Going beyond single-line comments
In Django you can effectively separate your hidden thoughts from code using comments. Your internal monologue is like a secret diary:
Was this article helpful?