Introduction
Django templates empower developers to construct dynamic and expressive HTML pages, offering a robust toolset to render content dynamically and manage variables passed from views.
Simple Template Example
1. Create a Template File :
# welcome.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Welcome Page</title> </head> <body> <h1>Welcome to Django Templates</h1> <p>This is a simple welcome page template.</p> </body> </html>
2. Render the Template in a View :
# welcome viewfrom django.shortcuts import renderdef welcome(request):
"""
This view renders the welcome template.
"""
return render(request, 'welcome.html')
# dynamic.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Page</title> </head> <body> <h1>Greetings, {{ username }}!</h1> <p>This page displays a dynamic greeting based on the provided username.</p> </body> </html>
# dynamic viewfrom django.shortcuts import render
def dynamic(request, username): """
This view renders the dynamic template with a username.
"""
return render(request, 'dynamic.html', {'username': username})