In this tutorial, we will delve into the Django Templating Engine, a crucial component of Django that allows the generation of dynamic HTML content in your web application. By the end of this tutorial, you will be able to create, use, and understand Django templates, and you will also be well-versed in best practices and tips for Django templating.
The Django Templating Engine works by replacing variable placeholders within a template with actual values that are passed to the template.
Django templates are HTML files that have extra syntax. Django templates are generally stored in a templates directory in your Django app. Let's create a simple Django template:
<!-- my_template.html -->
<html>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
In this example, {{ name }}
is a variable that will be replaced by Django.
To use the template, we need to load it, fill in the variables, and then render it. This is typically done in a Django view:
from django.shortcuts import render
def my_view(request):
context = {'name': 'Django'}
return render(request, 'my_template.html', context)
In this example, when my_view
is requested, Django will render my_template.html
, replacing {{ name }}
with 'Django'
.
<!-- home.html -->
<html>
<body>
<h1>Welcome to the {{ site_name }} website!</h1>
</body>
</html>
# views.py
from django.shortcuts import render
def home_view(request):
context = {'site_name': 'Amazing Django'}
return render(request, 'home.html', context)
In this example, when home_view
is requested, the text {{ site_name }}
in home.html
will be replaced with 'Amazing Django'
.
<!-- list.html -->
<html>
<body>
<ul>
{% for item in item_list %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
# views.py
from django.shortcuts import render
def list_view(request):
context = {'item_list': ['Item 1', 'Item 2', 'Item 3']}
return render(request, 'list.html', context)
In this example, the Django template tag {% for %}
is used to loop over item_list
and generate an HTML list.
In this tutorial, you learned how to create and use Django templates. You also learned about Django's template syntax, including variables and tags. You can now generate dynamic HTML content in your Django applications.
Consider exploring more advanced topics in Django templates, such as filters, inclusion tags, and custom template tags and filters.
Create a Django template that displays a list of books. Each book should have a title and an author. Test it with a list of books.
Create a Django template that displays a user's profile, including their name and email. Test it with a user object.
Enhance the book list template from exercise 1 to include a list of authors. Each author should have a name and a list of books they've written. Test it with a list of authors and books.
Note: Solutions to these exercises will depend on your specific data structures and are therefore not provided here.