What are Django Templates?

Django templates are HTML files with special syntax for inserting dynamic content. They separate presentation (HTML) from logic (Python), making your code cleaner and more maintainable.

Template Configuration

Configure templates in settings.py:

# settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        # ...
    }
]

Basic Template Syntax

Variables

Display variables using {{ }}:

<!-- template.html -->
<h1>Hello, {{ name }}!</h1>
<p>You are {{ age }} years old.</p>

# In view
context = {'name': 'Alice', 'age': 25}
return render(request, 'template.html', context)

Tags

Use tags for logic with {% %}:

<!-- Conditional -->
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
{% else %}
    <p>Please log in.</p>
{% endif %}

<!-- Loop -->
{% for item in items %}
    <li>{{ item.name }}</li>
{% endfor %}

Template Filters

Modify variable output:

{{ name|upper }}           # Convert to uppercase
{{ name|lower }}           # Convert to lowercase
{{ text|truncatewords:10 }} # Truncate to 10 words
{{ date|date:"Y-m-d" }}     # Format date
{{ value|default:"N/A" }}   # Default value

Template Inheritance

Create base templates and extend them:

<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    {% block content %}
    {% endblock %}
</body>
</html>

<!-- page.html -->
{% extends "base.html" %}

{% block title %}Page Title{% endblock %}

{% block content %}
    <h1>Page Content</h1>
{% endblock %}

Including Templates

Include other templates:

{% include "header.html" %}

<h1>Main Content</h1>

{% include "footer.html" %}

Common Template Tags

for Loop

{% for item in items %}
    <p>{{ item }}</p>
{% empty %}
    <p>No items available.</p>
{% endfor %}

{% for item in items %}
    {{ forloop.counter }}  # 1, 2, 3...
    {{ forloop.first }}    # True for first item
    {{ forloop.last }}     # True for last item
{% endfor %}

if/elif/else

{% if user.age >= 18 %}
    <p>Adult</p>
{% elif user.age >= 13 %}
    <p>Teenager</p>
{% else %}
    <p>Child</p>
{% endif %}

URL Tag

Generate URLs dynamically:

<a href="{% url 'home' %}">Home</a>
<a href="{% url 'user_profile' user_id=user.id %}">Profile</a>

Static Files

Load and use static files:

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">
<img src="{% static 'images/logo.png' %}" alt="Logo">

Custom Template Tags

Create custom tags:

# templatetags/custom_tags.py
from django import template

register = template.Library()

@register.simple_tag
def multiply(a, b):
    return a * b

# In template
{% load custom_tags %}
{% multiply 5 3 as result %}
{{ result }}  # 15

Best Practices

  • Use template inheritance: Avoid code duplication
  • Keep logic in views: Templates should only display data
  • Use filters: Format data in templates, not views
  • Organize templates: Use subdirectories for large projects
  • Escape user input: Django auto-escapes, but be aware

Next Steps

Learn about Django Views to pass data to templates, or explore forms for user input.