Templates
Send real HTML pages, with data inserted by Django’s template language.
What you will learn
- Render an HTML template
- Pass data to it
- Use template tags
Render a template
Returning plain text is fine for a test, but real pages are HTML. Django keeps the HTML in separate template files so your design stays out of your Python code. You show one with the render() helper, and you hand it a context — a dictionary of data the page can display.
# views.py
from django.shortcuts import render
def home(request):
products = ["Keyboard", "Mouse", "Monitor"]
return render(request, "home.html", {"products": products})render() takes three things: the request, the template file name ("home.html"), and the context dictionary {"products": products}. The dictionary key "products" becomes a variable named products that the template can use. So the list ["Keyboard", "Mouse", "Monitor"] is now available inside the HTML.
The template is an HTML file that can mix in data using Django’s template language. Save it inside the app’s templates/ folder:
<!-- templates/home.html -->
<h1>Our Products</h1>
<ul>
{% for product in products %}
<li>{{ product }}</li>
{% endfor %}
</ul>The {% for product in products %} … {% endfor %} loops once over each item in the products list we passed in. Inside the loop, {{ product }} prints the current item. So three products become three <li> items.
Note: Output (the HTML the browser shows): Our Products • Keyboard • Mouse • Monitor The view sent the list; the template looped over it and printed each one as a bullet.
| Template syntax | Does |
|---|---|
{{ value }} | Print a value |
{% for x in list %} | Loop |
{% if condition %} | Condition |
{% extends %} | Use a base layout |
Q. In a Django template, how do you print a variable?
✍️ Practice
- Render a template that shows a list passed from the view.
- Add an
{% if %}to show a message when the list is empty.
🏠 Homework
- Make a base layout and have a page extend it with {% extends %}.