️ About Templates in Django: Making Your Web Pages Dynamic and Beautiful
In Django, templates are the way you create the HTML pages that users see — but with dynamic content! They let you combine HTML with data from your views to build powerful, reusable web pages.
Let’s dive into what Django templates are and how to use them.
What Is a Django Template?
A template is basically an HTML file with placeholders (variables and tags) that Django fills with real data when rendering the page. This separation of design (template) and logic (views/models) follows the MVC (or MVT) pattern, making your app easier to manage.
️ Creating a Template File
By convention, templates are stored in a folder named templates
inside your app directory or project root.
Example project structure:
✨ Template Syntax Basics
Django templates use special syntax for variables and logic:
-
Variables: Display dynamic data with
{{ variable_name }}
-
Tags: Control logic with
{% tag %}
(loops, conditions, includes)
Example home.html
:
Rendering Templates in Views
Use Django’s render()
function to send data to a template and return the result as a response:
When users visit this view, they see a personalized page with the item list.
Template Inheritance: DRY Your HTML
To avoid repeating the same HTML (header, footer) on every page, Django uses template inheritance.
Create a base template:
Then extend it in other templates:
Other Useful Template Features
-
Filters: Modify variables, e.g.,
{{ name|lower }}
-
Includes: Insert reusable snippets
{% include "navbar.html" %}
-
Comments:
{# This is a comment #}
ignored by Django
Summary: Why Use Templates?
Benefit | Explanation |
---|---|
Separation of concerns | Keep HTML separate from Python logic |
Reusability | Use inheritance and includes |
Dynamic content rendering | Easily display data from your views |
Cleaner code | Simple syntax for logic and variables |