0
0
DjangoConceptBeginner · 3 min read

What is Template in Django: Simple Explanation and Example

In Django, a template is a text file that defines the structure or layout of a web page using HTML combined with Django Template Language. It separates the design (HTML) from the Python code, allowing dynamic content to be inserted easily when rendering web pages.
⚙️

How It Works

Think of a Django template like a blueprint for a house. It shows where each room (or piece of content) should go, but it doesn't build the house itself. When a user visits a website, Django takes this blueprint and fills in the rooms with actual furniture and decorations (dynamic data) to create a complete, personalized page.

The template uses simple tags and placeholders to mark where dynamic content should appear. When Django renders the template, it replaces these placeholders with real data from your Python code, producing a full HTML page that the browser can display.

💻

Example

This example shows a basic Django template that displays a greeting message with a user's name passed from the Python view.

django + python
<!-- greeting.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Greeting Page</title>
</head>
<body>
    <h1>Hello, {{ user_name }}!</h1>
</body>
</html>

# views.py
from django.shortcuts import render

def greet(request):
    context = {'user_name': 'Alice'}
    return render(request, 'greeting.html', context)
Output
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Greeting Page</title> </head> <body> <h1>Hello, Alice!</h1> </body> </html>
🎯

When to Use

Use Django templates whenever you want to create web pages that show dynamic content, like user names, lists, or data from a database. Templates help keep your design separate from your Python code, making your project easier to manage and update.

For example, use templates to build pages like user profiles, product listings, or blog posts where the content changes based on who visits or what data is available.

Key Points

  • Django templates combine HTML with special tags to insert dynamic data.
  • They separate the website’s design from the Python logic.
  • Templates are rendered by Django to produce complete HTML pages.
  • They make it easy to update the look without changing the code.

Key Takeaways

A Django template is a file that defines the HTML layout with placeholders for dynamic content.
Templates separate the website’s design from Python code, improving organization.
Django replaces template placeholders with real data when rendering pages.
Use templates to build dynamic web pages like user profiles or product lists.
Templates make updating the website’s look easier without changing backend code.