Working with Templates in Django: Bringing Your Web Pages to Life
Templates in Django are your go-to tool for designing web pages that display dynamic content. They separate your HTML from your backend code, making your project organized and scalable.
This post will guide you through how to work effectively with Django templates.
️ What Is a Template?
A template is an HTML file with placeholders for dynamic content. When a view renders a template, Django fills in these placeholders with data and sends the resulting HTML to the user’s browser.
️ Setting Up Your Templates Folder
By default, Django looks for templates in a directory named templates
. You can create this folder inside your app or project directory.
Example structure:
Tip: Organize templates by app name inside the
templates
folder to avoid conflicts.
✨ Using Variables in Templates
Placeholders for variables are marked with double curly braces: {{ variable_name }}
.
Example home.html
:
Rendering a Template from a View
In your view function, use the render()
shortcut:
context
is a dictionary where keys are variable names used in the template, and values are their data.
Template Inheritance
Avoid repeating code by creating a base template with common elements like header and footer.
base.html
:
home.html
(extends base):
️ Control Structures in Templates
Templates support logic tags like:
-
If statements:
-
For loops:
Template Filters
Filters modify variables’ output, e.g.,
Summary
Template Feature | Usage Example |
---|---|
Variable | {{ variable }} |
If Condition | {% if condition %}...{% endif %} |
For Loop | {% for item in list %}...{% endfor %} |
Template Inheritance | {% extends "base.html" %} |
Filters | `{{ variable |