HTML Templates
Render HTML templates instead of plain text — use Django template engine to serve dynamic HTML pages from your views.
HTML Templates
Returning plain text with HttpResponse is not practical. Django's template engine lets you render full HTML pages and inject dynamic data.
Creating a Templates Folder
djangoblog/
├── templates/
│ ├── homepage.html
│ └── about.html
├── manage.py
└── djangoblog/
└── settings.py
Configuring Templates
# djangoblog/settings.py
TEMPLATES = [
{
'DIRS': [os.path.join(BASE_DIR, 'templates')],
# ... other settings
},
]
A Simple Template
<!-- templates/homepage.html -->
<html>
<head>
<title>Django Blog</title>
</head>
<body>
<h1>Welcome to the Django Blog</h1>
<p>This is the homepage.</p>
</body>
</html>
Rendering Templates in Views
# djangoblog/views.py
from django.shortcuts import render
def homepage(request):
return render(request, 'homepage.html')
def about(request):
return render(request, 'about.html')
render() takes the request, the template name, and an optional context dictionary. It returns an HttpResponse with the rendered HTML.
Passing Data to Templates
# View
def homepage(request):
return render(request, 'homepage.html', {
'title': 'Welcome',
'blog_name': 'Django Blog'
})
<!-- Template -->
<h1>{{ blog_name }}</h1>
<p>{{ title }}</p>
Double curly braces {{ variable }} output the value of a context variable in the template.
Key Takeaways
render(request, template, context)renders an HTML template- Templates live in a
templates/directory configured insettings.py - Use
{{ variable }}to display dynamic data passed from the view - The context is a Python dictionary passed as the third argument to
render()