Django Template Syntax: Variables, Filters, Tags, and Custom Extensions
1. Core Syntax
Django templates use two key syntax patterns:
{{ }}for variable interpolation{% %}for logical operations (loops, conditions, etc.)
# views.py
from django.shortcuts import render
import datetime
def get_current_timestamp(request):
profile = {"username": "moon", "age": 22}
current_datetime = str(datetime.datetime.now())
return render(request, "timestamp.html", {"current_time": current_datetime, "profile": profile})
<!-- timestamp.html -->
<h1>{{ current_time }}</h1>
<h1>{{ profile.username }}</h1>
<h1>{{ profile.age }}</h1>
<!-- Output -->
<!-- 2025-03-10 14:25:30.123456 -->
<!-- moon -->
<!-- 22 -->
2. Variable Usage
The dot notation is central to accessing nested data structures in Django templtaes. Syntax: {{ variable_name }}
# views.py
def display_index(request):
sample_dict = {2: 4, "title": "moon"}
# Method 1: Explicit context
return render(request, "index.html", {"data_dict": sample_dict})
# Method 2: Local variables (includes all variables in scope)
return render(request, "index.html", locals())
# Supported data types to pass to templates
text = "Hi there!"
numbers = [3, 5, 7, ["x", "xyz"]]
sample_dict = {2: 4, "title": "moon"}
coords = (10, 20, 30)
distinct_values = {1, 3, 5, 7}
def greet_user():
return "Welcome back!"
class Product:
def __init__(self, name, price):
self.product_name = name
self.price = price
def get_discount_price(self):
return self.price * 0.9
product_obj = Product("Laptop", 999.99)
Variable Types & Access Methods
| Type | View Definition | Template Access Examples | Output |
|---|---|---|---|
| String | text = "Hi there!" |
{{ message }} |
Hi there! |
| List | numbers = [3,5,7,["x","xyz"]] |
{{ num_list.1 }} {{ num_list.3.0 }} |
5 x |
| Dictionary | sample_dict = {2:4, "title":"moon"} |
{{ data_dict.title }} |
moon |
| Tuple | coords = (10,20,30) |
{{ coordinates.2 }} |
30 |
| Set | distinct_values = {1,3,5,7} |
{{ unique_values }} |
{1,3,5,7} |
| Function | def greet_user(): ... |
{{ greet }} |
Welcome back! |
| Object | product_obj = Product(...) |
{{ item.product_name }} {{ item.get_discount_price }} |
Laptop 899.991 |
Note: All iterable types can be looped over using {% for item in iterable %} <p>{{ item }}</p> {% endfor %}.