DEV Community

Cover image for How to Create Custom Template Tags in Django?
Syeda Maham Fahim
Syeda Maham Fahim

Posted on

1 1 1

How to Create Custom Template Tags in Django?

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:

Django Template

This template will get data from the view, like this:

View.py

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:

Website

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})
Enter fullscreen mode Exit fullscreen mode

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

  1. Create the templatetags folder inside your courses app:

Your folder structure will look like this:

   courses/
       ├── templatetags/
           ├── __init__.py
           └── course_tags.py
Enter fullscreen mode Exit fullscreen mode
  1. 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()
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

  1. Once you define a template tag (like total_courses, available_courses, or enrolled_students), you can use it in multiple places across your app without repeating the same logic in each view.

  2. 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

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 🐬

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
john_matthew_82c0880ee1c1 profile image
John Matthew

Nicely done, thank you.

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay