Table of Contents
Django template basic example
Question: Show total number of courses
What is a template tag?
Why use template tag?
Step 1: Create template tags
Step 2: Load and use template tags in templates
Example 1: Display the total number of courses on the course list page
Example 2: Display the number of registered students on the course details page
Advantages of using template tags
Final output
Conclusion
Home Backend Development Python Tutorial How to Create Custom Template Tags in Django?

How to Create Custom Template Tags in Django?

Jan 27, 2025 am 08:10 AM

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Python 3.6 loading pickle file error ModuleNotFoundError: What should I do if I load pickle file '__builtin__'? Apr 02, 2025 am 06:27 AM

Loading pickle file in Python 3.6 environment error: ModuleNotFoundError:Nomodulenamed...

What is the reason why pipeline files cannot be written when using Scapy crawler? What is the reason why pipeline files cannot be written when using Scapy crawler? Apr 02, 2025 am 06:45 AM

Discussion on the reasons why pipeline files cannot be written when using Scapy crawlers When learning and using Scapy crawlers for persistent data storage, you may encounter pipeline files...

See all articles