How to Use Template Tags in Django: Syntax and Examples
In Django, use
{% tag_name %} syntax to add template tags inside HTML templates. Template tags let you add logic like loops, conditions, and variable handling to control what content is shown dynamically.Syntax
Django template tags are enclosed in {% %} delimiters. The basic pattern is {% tag_name [arguments] %}. Tags can control flow, load libraries, or output data.
For example, {% if condition %} starts a condition, and {% endfor %} ends a loop.
django
{% tag_name argument1 argument2 %}
{% if user.is_authenticated %}
Hello, {{ user.username }}!
{% endif %}Example
This example shows how to use the for and if template tags to display a list of items only if the list is not empty.
django
{% if items %}
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% else %}
<p>No items found.</p>
{% endif %}Output
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
Common Pitfalls
- Forgetting to close tags like
{% endif %}or{% endfor %}causes template errors. - Using variable syntax
{{ }}inside{% %}tags is incorrect. - Not loading custom tags with
{% load tag_library %}before using them.
django
{% if user.is_authenticated %}
Welcome!
<!-- Missing {% endif %} here causes error -->
<!-- Correct usage -->
{% if user.is_authenticated %}
Welcome!
{% endif %}Quick Reference
| Template Tag | Purpose | Example |
|---|---|---|
| if | Conditionally render content | {% if user.is_staff %}Admin{% endif %} |
| for | Loop over a list | {% for item in list %}{{ item }}{% endfor %} |
| load | Load custom tag libraries | {% load static %} |
| block | Define a block for template inheritance | {% block content %}...{% endblock %} |
| include | Include another template | {% include 'header.html' %} |
Key Takeaways
Use {% %} to write template tags that add logic to Django templates.
Always close tags like {% endif %} and {% endfor %} to avoid errors.
Use {{ }} only for outputting variables, not inside template tags.
Load custom tags with {% load %} before using them.
Common tags include if, for, load, block, and include.