This content originally appeared on DEV Community and was authored by SSL Dev
Django Template Tags are powerful tools that allow developers to add logic within HTML templates. They enable the display of dynamic data and the implementation of various features such as loops, conditional statements, and more.
Basic Syntax
Template tags are enclosed within {% %}
. For example:
{% for item in items %}
<p>{{ item.name }}</p>
{% endfor %}
Common Template Tags
-
for
- Used to loop over a sequence.
- Example:
{% for user in user_list %} <p>{{ user.username }}</p> {% endfor %}
-
if
- Used for conditional statements.
- Example:
{% if user.is_authenticated %} <p>Welcome, {{ user.username }}</p> {% else %} <p>Please log in.</p> {% endif %}
-
block and extends
- Used for template inheritance.
- Example:
<!-- base.html --> <html> <head><title>{% block title %}My Site{% endblock %}</title></head> <body> {% block content %}{% endblock %} </body> </html> <!-- home.html --> {% extends "base.html" %} {% block title %}Home{% endblock %} {% block content %} <h1>Welcome to Home Page</h1> {% endblock %}
-
include
- Used to include another template.
- Example:
{% include "header.html" %}
Custom Template Tags
Custom template tags can be created to extend the functionality.
- Create a
templatetags
directory inside an app. - Create a Python module and define the custom tag.
Example:
from django import template
register = template.Library()
@register.simple_tag
def current_time(format_string):
from datetime import datetime
return datetime.now().strftime(format_string)
Usage in template:
{% load custom_tags %}
<p>Current time: {% current_time "%Y-%m-%d %H:%M:%S" %}</p>
Advanced Template Tags
-
with
- Assigns a value to a variable within the template.
- Example:
{% with total=business.employees.count %} <p>Total employees: {{ total }}</p> {% endwith %}
-
cycle
- Cycles between values.
- Example:
{% for row in rows %} <tr class="{% cycle 'odd' 'even' %}">{{ row }}</tr> {% endfor %}
-
firstof
- Outputs the first non-empty variable.
- Example:
<p>{% firstof var1 var2 'default' %}</p>
Conclusion
Django Template Tags provide a robust way to add logic and dynamic content to templates. Mastering them can significantly enhance the development process.
This content originally appeared on DEV Community and was authored by SSL Dev

SSL Dev | Sciencx (2025-01-26T00:23:16+00:00) Beginners Guide to Django Template Tags. Retrieved from https://www.scien.cx/2025/01/26/beginners-guide-to-django-template-tags/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.