Home > Backend Development > Python Tutorial > How to Create Custom Template Tags in Django?

How to Create Custom Template Tags in Django?

Susan Sarandon
Release: 2025-01-27 08:10:10
Original
596 people have browsed it

Django template tag: simplify data display and improve code reusability

In Django development, templates are used to dynamically render data into HTML pages. This article will introduce how to use Django template tags to simplify data display logic and avoid duplicating code in views.

Django template basic example

Suppose you have a simple course list HTML template:

How to Create Custom Template Tags in Django?

The corresponding view code is as follows:

How to Create Custom Template Tags in Django?

The

view passes the course data to the template, which is ultimately displayed on the web page as follows:

How to Create Custom Template Tags in Django?

Question: Show total number of courses

Now, let’s say you need to display the total number of courses on a web page. One way is to add calculation logic in the view:

def course_list(request):
    total_courses = Course.objects.count()
    return render(request, 'courses.html', {'courses': courses, 'total_courses': total_courses})
Copy after login
Copy after login

But if your website has multiple pages (such as blog page, author page, instructor page) that all need to display the total number of courses, you need to repeat this logic in each view, which will lead to redundant code and difficult to maintain . At this time, Django template tags come in handy.

What is a template tag?

To put it simply, Django template tags are special tags that allow you to add custom functionality to the Django template system. It can improve code reusability and avoid writing the same logic repeatedly in views.

Why use template tag?

Suppose your course app needs to display the following data:

  • Total number of courses
  • Number of courses available
  • Number of registered students

Instead of adding calculation logic in every view, use template tags to simplify things.

Step 1: Create template tags

  1. Create templatetags folder: Create templatetagsfolder under your courses app:

Your folder structure is as follows:

<code>   courses/
       ├── templatetags/
           ├── __init__.py
           └── course_tags.py</code>
Copy after login
  1. In the course_tags.py file, define the template tags that calculate the total number of courses, the number of available courses, and the number of registered 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()
Copy after login

Step 2: Load and use template tags in templates

Now you can load and use these custom tags in your HTML template to display relevant data.

Example 1: Display the total number of courses on the course list page

In the course_list.html template, load the custom tags and use them to display the total number of courses and the number of available courses:

{% load course_tags %}

<h1>所有课程</h1>

<p>总课程数:{% total_courses %}</p>
<p>可用课程数:{% available_courses %}</p>

{% for course in courses %}
    - {{ course.name }} - {{ course.description }}
{% endfor %}
Copy after login

This template will display:

  • Total number of courses
  • Number of courses available

Example 2: Display the number of registered students on the course details page

On the course details page, you can use the enrolled_students template tag to display the number of registered students for a specific course:

def course_list(request):
    total_courses = Course.objects.count()
    return render(request, 'courses.html', {'courses': courses, 'total_courses': total_courses})
Copy after login
Copy after login
The

enrolled_students tag receives course.id as a parameter and returns the number of registered students for the course.

Advantages of using template tags

  1. After defining the template tag, it can be reused in multiple places in the application without having to write the same logic repeatedly in each view.
  2. If you need to modify how course counts are calculated, just update the template tags without modifying each view or template.

Final output

How to Create Custom Template Tags in Django?

Conclusion

This article demonstrates through examples how to use template tags in Django to avoid duplicating the logic of adding courses and student counts in views. Template tags improve code reusability and maintainability.


Contact - @syedamahamfahim ?

The above is the detailed content of How to Create Custom Template Tags in Django?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template