Templates and Static Files
Django Template Language (DTL), context variables, and loading static assets.
🧑🏫 Sabse pehle — simple mein samjho#
React mein jaise tum {data.title} likhte ho HTML ke andar, waise hi Django mein Django Template Language (DTL) hoti hai. Tum apne views se data bhejte ho, aur HTML files mein {{ data.title }} likh kar usay display karte ho. Sabse acchi baat ye hai ki tum ek base layout (jaise navbar aur footer) bana kar baaki saare pages mein usay extend kar sakte ho, jisse code repeat nahi hota. CSS, Images, aur JS files ko Django "Static Files" kehta hai, jinko load karne ka ek khaas tareeqa hota hai.
1. Django Template Language (DTL)#
DTL has two main syntaxes you will use constantly:
- Variables
{{ }}: Outputs data passed from the view's context dictionary. - Tags
{% %}: Executes logic (like if-statements, for-loops, and template inheritance).
Displaying Variables#
<!-- If context = {'post': post_object, 'user': 'Tarun'} -->
<h1>{{ post.title }}</h1>
<p>Written by: {{ user }}</p>
<!-- Accessing dictionary keys, object attributes, or list indexes is all done with a DOT -->
<p>{{ post.author.username }}</p>
Control Flow (Logic)#
<!-- For Loops -->
<ul>
{% for post in posts %}
<li>{{ post.title }}</li>
{% empty %}
<li>No posts found!</li>
{% endfor %}
</ul>
<!-- If Statements -->
{% if user.is_authenticated %}
<a href="/logout">Logout</a>
{% else %}
<a href="/login">Login</a>
{% endif %}
2. Template Inheritance (DRY - Don't Repeat Yourself)#
Instead of copying the Navbar and HTML <head> into every single file, create a base.html.
base.html
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
</head>
<body>
<nav>Navbar goes here</nav>
<!-- This is a placeholder block -->
{% block content %}{% endblock %}
<footer>Footer goes here</footer>
</body>
</html>
home.html
<!-- Tell this template to use base.html as its skeleton -->
{% extends "base.html" %}
<!-- Inject this HTML into the placeholder block -->
{% block content %}
<h1>Welcome to the homepage!</h1>
{% endblock content %}
3. Dynamic URLs#
Never hardcode URLs (like href="/blog/post/1/"). If you ever change the URL pattern in urls.py, all your hardcoded links will break! Instead, use the {% url %} tag, providing the name you gave the path in urls.py.
<!-- Assuming path('post/<int:pk>/', views.detail, name='post-detail') -->
<a href="{% url 'post-detail' post.id %}">Read More</a>
4. Static Files (CSS, JS, Images)#
Django handles static files securely. By default, it looks for a folder named static inside your apps.
- Load the static library at the very top of your HTML file.
- Use the
{% static %}tag to generate the absolute URL to your CSS or image file.
{% load static %}
<!DOCTYPE html>
<html>
<head>
<!-- Generates a link like: /static/blog/main.css -->
<link rel="stylesheet" href="{% static 'blog/main.css' %}">
</head>
<body>
<img src="{% static 'blog/logo.png' %}" alt="Logo">
</body>
</html>