Templates Introduction
Templates are HTML files with placeholders that Django fills in.
Syntax
render(request, "app/template.html", context)A template is an HTML file that mixes static markup with special tags Django replaces at render time. By convention, templates live in a templates/ folder inside each app, namespaced by the app name.
Return one from a view with the render() shortcut, passing a context dictionary of variables.
Example
# blog/views.py
from django.shortcuts import render
def index(request):
context = {"title": "My Blog", "count": 3}
return render(request, "blog/index.html", context)
# blog/templates/blog/index.html
# <h1>{{ title }}</h1>
# <p>{{ count }} posts</p>When to use it
- A developer creates a templates/ folder inside the blog app to store all HTML files for that app.
- A team configures TEMPLATES in settings.py to point Django at a global templates directory shared across apps.
- A developer uses {{ variable }} syntax in a template to display user-specific data without writing Python in HTML.
More examples
Configure templates directory
Configures Django to look for templates in a project-level templates/ directory.
# settings.py
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [BASE_DIR / "templates"],
"APP_DIRS": True,
"OPTIONS": {"context_processors": [...]},
}
]Render template with context
Passes a queryset to a template through the context dictionary using render().
from django.shortcuts import render
from .models import Product
def product_list(request):
products = Product.objects.filter(available=True)
return render(request, "shop/product_list.html", {"products": products})Basic template with variable
Uses double-brace {{ }} syntax to output context variables inside an HTML template.
<!DOCTYPE html>
<html>
<head><title>{{ page_title }}</title></head>
<body>
<h1>{{ page_title }}</h1>
<p>Welcome, {{ user.username }}!</p>
</body>
</html>
Discussion