Working with Templates

01-Feb-2024

Effortlessly work with Django templates using our quick guide. Learn to structure and render dynamic content for seamless integration into your web applications.

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 view
from django.shortcuts import render


def welcome(request):
"""
This view renders the welcome template.
"""

return render(request, 'welcome.html')

   
Passing Dynamic Data to Templates

1. Modify Template to Display Dynamic Data :



# 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>

      
2. Update the View to Pass Data  :



# dynamic view
from django.shortcuts import render

def dynamic(request, username): """
This view renders the dynamic template with a username.
"""

return render(request, 'dynamic.html', {'username': username})
   
    - The render function now includes a dictionary with the key 'username' and its corresponding value to pass dynamic data to the template.

Comments