Templates keep the look of a website separate from its data and logic. This makes it easier to change how things look without breaking how they work.
0
0
Why templates separate presentation in Django
Introduction
When you want designers to work on the website look without touching the code.
When you need to show the same data in different styles or layouts.
When you want to keep your code clean and organized by separating logic and design.
When you want to reuse the same page structure with different content.
When you want to update the website appearance quickly without changing backend code.
Syntax
Django
{% block content %}
<!-- HTML and template tags here -->
{% endblock %}Templates use special tags like {% block %} and {{ variable }} to insert data.
The template files usually end with .html and contain mostly HTML with some template code.
Examples
This example shows how to insert variables into HTML using double curly braces.
Django
<h1>{{ title }}</h1>
<p>Welcome, {{ user_name }}!</p>This example shows how to use a condition to show different content based on user login status.
Django
{% if user.is_authenticated %}
<p>Hello, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}Sample Program
This example shows two templates: a base template with the page structure and a home page that fills in the content and title. This separation helps keep design and content organized.
Django
{# base.html #}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<main>
{% block content %}
<!-- Content will go here -->
{% endblock %}
</main>
<footer>
<p>© 2024 My Website</p>
</footer>
</body>
</html>
{# home.html #}
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h2>Welcome to the Home Page</h2>
<p>Hello, {{ user_name }}!</p>
{% endblock %}OutputSuccess
Important Notes
Templates help teams work better by letting designers and developers focus on their parts.
Changing the look is safer and faster because you do not touch the backend code.
Using template inheritance avoids repeating the same HTML in many files.
Summary
Templates separate how a page looks from how it works.
This makes websites easier to build, change, and maintain.
Template inheritance helps reuse common page parts like headers and footers.