Django

Django Templates

Template system

Django Templates

Django's template system allows you to separate the design of your pages from the Python code. Templates are HTML files with special syntax for dynamic content.

Create Templates Directory

First, create a templates directory in your app:

myapp/
    templates/
        myapp/
            index.html

Configure Templates in Settings

Make sure TEMPLATES is configured in settings.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        ...
    },
]

Template Syntax

Django templates use special syntax:

<!-- Variables -->
<h1>{{ name }}</h1>

<!-- Tags -->
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
{% endif %}

<!-- Loops -->
{% for item in items %}
    <li>{{ item }}</li>
{% endfor %}

Template Inheritance

Create a base template:

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

Extend it in child templates:

{% extends "base.html" %}

{% block title %}My Page{% endblock %}

{% block content %}
    <h1>Hello, World!</h1>
{% endblock %}