About Lesson
2.5.1 Django Template Language (DTL) Basics
Django uses a powerful templating engine called Django Template Language (DTL). Templates allow dynamic content to be rendered using data passed from views.
Basic Syntax
-
- Variables:
Hello, {{ user_name }}!
-
- Tags: Control logic like loops and conditionals:
{% if user_name %}
Welcome back, {{ user_name }}!
{% else %}
Welcome, Guest!
{% endif %}
-
- Filters: Modify data for display:
{{ user_name|upper }}
2.5.2 Rendering HTML with Templates
-
- Template Directory:
myapp/
templates/
myapp/
index.html
-
- Load and Render Templates: Update your view:
from django.shortcuts import render
def index(request):
context = {'user_name': 'Alice'}
return render(request, 'myapp/index.html', context)
-
- Template Example:
myapp/templates/myapp/index.html
:
- Template Example:
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Hello, {{ user_name }}!</h1>
</body>
</html>
2.5.3 Template Inheritance
Why Use Inheritance?
Inheritance allows you to define a base structure for your HTML pages and extend it in child templates. This promotes reusability and consistent design.
Defining a Base Template
templates/myapp/base.html
:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Website{% endblock %}</title>
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<main>
<!-- {% block content %}{% endblock %} -->
</main>
<footer>
<p>Copyright 2024</p>
</footer>
</body>
</html>
Extending the Base Template
templates/myapp/index.html
:
{% extends 'myapp/base.html' %}
{% block title %}Welcome{% endblock %}
{% block content %}
<h2>Welcome to My Website</h2>
<p>This is the homepage.</p>
{% endblock %}
Rendering the Extended Template
The index.html
template inherits the structure from base.html
while defining its specific content.
Join the conversation