If you have worked with Django, you must have used templates. Templates in Django are simply HTML files that can receive data from the views and display it on the website.
Basic Example of Django Template
Imagine you have an HTML template like this:
This template will get data from the view, like this:
In the example above, we have a template called courses
where the data (like course names) is being passed from the views.py
file. The output on the website will look like this:
Problem: Displaying Course Count
Now, let’s say you want to show the total number of courses on the website. You may think of adding the logic to the view, and that’s correct. You would do something like this in your views.py
:
def course_list(request):
total_courses = Course.objects.count()
return render(request, 'courses.html', {'courses': courses, 'total_courses': total_courses})
But what if you have multiple pages on your website, like a blog page, author page, instructor page, and you want to display the course count on all of them?
You would need to add the logic in each of the views, and that can get messy. This is where template tags come in.
What is a Template Tag?
In simple terms:
A template tag in Django is a special kind of tag that allows you to add custom functionality within Django’s template system.
Template tags make it easier to reuse logic across different templates, without having to repeat the same code in your views.
Why Use Template Tags?
Let’s say you have a courses app where you want to display:
- Total number of courses
- Number of available courses
- Number of enrolled students
Instead of adding this logic in each view, you can use template tags to make it easier.
Step 1: Create a Template Tag
-
Create the
templatetags
folder inside yourcourses
app:
Your folder structure will look like this:
courses/
├── templatetags/
├── __init__.py
└── course_tags.py
- Inside the
course_tags.py
file, define a template tag that will calculate and return the total number of courses, number of available courses, and number of enrolled students.
from django import template
from courses.models import Course
register = template.Library()
@register.simple_tag
def total_courses():
return Course.objects.count()
@register.simple_tag
def available_courses():
return Course.objects.filter(is_available=True).count()
@register.simple_tag
def enrolled_students(course_id):
course = Course.objects.get(id=course_id)
return course.enrolled_students.count()
Step 2: Load and Use the Template Tags in Your Templates
Now, you can use these template tags in your HTML templates to display relevant data on different pages related to courses.
Example 1: Displaying Course Count on the Course List Page
In your course_list.html
template, you can load the custom tags and use them to display the total number of courses and available courses.
{% load course_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Course List</title>
</head>
<body>
<h1>All Courses</h1>
<p>Total courses: {% total_courses %}</p>
<p>Available courses: {% available_courses %}</p>
<ul>
{% for course in courses %}
<li>{{ course.name }} - {{ course.description }}</li>
{% endfor %}
</ul>
</body>
</html>
This template will show:
- The total number of courses.
- The number of available courses.
Example 2: Displaying Enrolled Students on a Course Detail Page
For the course details page, you can use the enrolled_students
template tag to show how many students are enrolled in a specific course.
{% load course_tags %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ course.name }}</title>
</head>
<body>
<h1>{{ course.name }}</h1>
<p>{{ course.description }}</p>
<p>Enrolled students: {% enrolled_students course.id %}</p>
<h2>Enroll Now</h2>
<!-- Add enrollment form here -->
</body>
</html>
Here, the enrolled_students
tag takes the course.id
and returns the number of students enrolled in that specific course.
Benefits of Using Template Tags in This Example
Once you define a template tag (like
total_courses
,available_courses
, orenrolled_students
), you can use it in multiple places across your app without repeating the same logic in each view.If you want to change how the course count is calculated (e.g., if you add a new filter for "active" courses), you only need to update the tag, not every view or template.
Final Output
Conclusion
In this blog post, we used template tags in Django to avoid adding repetitive logic for counting courses and students in each view. Instead of manually passing the data from views, we created reusable template tags that can be used across multiple templates in the courses app.
Stay Connected - @syedamahamfahim 🐬
Top comments (1)
Nicely done, thank you.