Django Templates
Creating dynamic HTML pages with Django template system
🎨 What are Django Templates?
Django templates are HTML files that allow you to display dynamic content from your Python code. They use special syntax to insert variables, loops, and logic into your web pages.
<!-- templates/home.html -->
<h1>Hello, {{ name }}!</h1>
<p>Welcome to Django Templates.</p>
Output:
Hello, John!
Welcome to Django Templates.
Key Template Concepts
Variables
Display dynamic data in templates
{{ variable_name }}
Tags
Add logic like loops and conditions
{% if condition %}
...
{% endif %}
Filters
Modify variable display
{{ name|upper }}
Inheritance
Reuse template structure
{% extends "base.html" %}
🔹 Creating Your First Template
Templates are stored in a templates folder within your Django app. Here's how to create and use a basic template with variables and display dynamic content.
# views.py
from django.shortcuts import render
def home(request):
context = {
'name': 'John',
'age': 25
}
return render(request, 'home.html', context)
<!-- templates/home.html -->
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>User Profile</h1>
<p>Name: {{ name }}</p>
<p>Age: {{ age }}</p>
</body>
</html>
Output:
User Profile
Name: John
Age: 25
🔹 Template Tags - Loops
Use for loops to display lists of items in your templates:
# views.py
def products(request):
context = {
'items': ['Apple', 'Banana', 'Orange']
}
return render(request, 'products.html', context)
<!-- templates/products.html -->
<h2>Fruit List</h2>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Output:
Fruit List
- Apple
- Banana
- Orange
🔹 Template Tags - Conditionals
Use if statements to show content based on conditions:
<!-- templates/status.html -->
{% if user.is_authenticated %}
<p>Welcome back, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}
Output (when logged in):
Welcome back, john_doe!
🔹 Template Filters
Filters modify how variables are displayed in templates:
<!-- Common filters -->
<p>{{ name|upper }}</p> <!-- JOHN -->
<p>{{ name|lower }}</p> <!-- john -->
<p>{{ text|truncatewords:3 }}</p> <!-- First 3 words... -->
<p>{{ price|floatformat:2 }}</p> <!-- 19.99 -->
<p>{{ date|date:"Y-m-d" }}</p> <!-- 2024-01-15 -->
Output:
JOHN
john
First 3 words...
19.99
2024-01-15
🔹 Template Inheritance
Create a base template and extend it to avoid repeating code:
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<header>
<h1>My Website</h1>
</header>
{% block content %}
{% endblock %}
<footer>
<p>© 2025 My Site</p>
</footer>
</body>
</html>
<!-- templates/about.html -->
{% extends "base.html" %}
{% block title %}About Us{% endblock %}
{% block content %}
<h2>About Our Company</h2>
<p>We are a great company!</p>
{% endblock %}