CodeToLive

Django Templates

Django's template language is designed to be easy to use while providing powerful features for creating dynamic HTML. Templates allow you to separate presentation from business logic.

Template Basics

Django templates are text files with special syntax:

  • Variables: {{ variable }}
  • Tags: {% tag %}
  • Filters: {{ variable|filter }}
  • Comments: {# comment #}

Template Configuration

Configure templates in settings.py:


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
                

Template Inheritance

Django templates support inheritance with blocks:


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

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

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

{% block content %}
    <h1>Welcome to my page</h1>
    <p>This is my content.</p>
{% endblock %}
                

Template Variables

Access variables passed from views:


<h1>{{ book.title }}</h1>
<p>Author: {{ book.author }}</p>
<p>Price: ${{ book.price }}</p>
                

Template Tags

Common template tags:

for


<ul>
{% for book in books %}
    <li>{{ book.title }}</li>
{% empty %}
    <li>No books available.</li>
{% endfor %}
</ul>
                

if


{% if book.in_stock %}
    <p>Available</p>
{% elif book.expected_soon %}
    <p>Expected soon</p>
{% else %}
    <p>Out of stock</p>
{% endif %}
                

url


<a href="{% url 'book_detail' book.id %}">View Details</a>
                

include


{% include "includes/navbar.html" %}
                

Template Filters

Filters transform variable values:

  • {{ value|length }} - Length of the value
  • {{ value|lower }} - Convert to lowercase
  • {{ value|upper }} - Convert to uppercase
  • {{ value|title }} - Title case
  • {{ value|date:"D d M Y" }} - Format date
  • {{ value|truncatechars:50 }} - Truncate to 50 chars
  • {{ value|default:"Nothing" }} - Default value

Custom Filters

Create your own template filters:


# myapp/templatetags/custom_filters.py
from django import template

register = template.Library()

@register.filter(name='currency')
def currency(value):
    return f"${value:.2f}"
                

Usage in template:


{% load custom_filters %}

<p>Price: {{ book.price|currency }}</p>
                

Custom Tags

Create more complex template tags:


# myapp/templatetags/custom_tags.py
from django import template

register = template.Library()

@register.simple_tag
def current_time(format_string):
    return datetime.datetime.now().strftime(format_string)