Django Template Language (DTL)
Django Template Language (DTL) enables you to dynamically generate HTML. DTL separation of concerns ensures that code files handle logic, while templates format display strings.
1 Base Template inheritance
HTML — templates/base.html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<header>
<nav><a href="/">Home</a></nav>
</header>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
2 Child Template & Loops
HTML — templates/posts.html
{% extends "base.html" %}
{% block title %}All Blog Posts{% endblock %}
{% block content %}
<h1>Latest Posts</h1>
<ul>
{% for post in posts %}
<li>
<a href="{% url 'post-detail' post.id %}">{{ post.title }}</a>
- Written by: {{ post.author|default:"Anonymous" }}
</li>
{% empty %}
<li>No posts found.</li>
{% endfor %}
</ul>
{% endblock %}
3 Code Challenge
Challenge: Write a view that passes a list of active products to a template. In the template, use a loop to display the product name and price, and conditional tags (
if) to highlight products priced over $100.