Explain Codes LogoExplain Codes Logo

How to put comments in Django templates?

python
django-templates
commenting-best-practices
debugging
Nikita BarsukovbyNikita Barsukov·Feb 20, 2025
TLDR

In Django templates, {% comment %} ... {% endcomment %} is used for multi-line comments while {# comment #} is used for single-line comments:

{% comment %}This line is on vacation!{% endcomment %} {# This line is taking a nap! #}

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:

  1. Avoid using HTML comment syntax (<!-- comment -->) as these become visible in the page's source code. Sneaky, but not sneaky enough!
  2. 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.
  3. 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.
  4. 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:

{% comment "Debug Hint: Missing semicolon anyone?" %} {% include 'suspected_problem_template.html' %} {% endcomment %}

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:

One small step for a template, One giant leap for an app... {# That's one small step for a man... sorry couldn't resist! #}