️ 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:

arduino
myproject/
myapp/
templates/
home.html

✨ 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:

html
<!DOCTYPE html>
<html>
<head>
<title>My Django Site</title>
</head>
<body>
<h1>Welcome, {{ user_name }}!</h1>

{% if items %}
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% else %}
<p>No items to display.</p>
{% endif %}
</body>
</html>


Rendering Templates in Views

Use Django’s render() function to send data to a template and return the result as a response:

python
from django.shortcuts import render

def home(request):
context = {
'user_name': 'Alice',
'items': ['Apples', 'Bananas', 'Cherries']
}
return render(request, 'home.html', context)

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:

html
<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<header>
<h1>My Website Header</h1>
</header>

<main>
{% block content %}{% endblock %}
</main>

<footer>
<p>Footer info here</p>
</footer>
</body>
</html>

Then extend it in other templates:

html
<!-- templates/home.html -->
{% extends "base.html" %}

{% block title %}Home - My Site{% endblock %}

{% block content %}
<h2>Welcome to the homepage!</h2>
{% endblock %}


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

Leave a Reply

Your email address will not be published. Required fields are marked *