Template Partials
Part of the JSON APIs section of Coddy's Django journey. Lesson 14 of 19.
A script does not always want JSON. After adding a task it may ask the server for that task's ready-made <li> and drop it into the list. A template already draws that row, so the server should reuse it.
Django 6.0 added template partials: a named piece of a template you can also render alone. Wrap it in {% partialdef %}; inline also draws it in place, on every turn of a loop. A view renders only the piece with the template's name, #, and the partial's name:
{% partialdef cart-total inline %}
<strong>{{ cart.total }}</strong>
{% endpartialdef %}return render(request, "shop/cart.html#cart-total", {"cart": cart})The context must hold what the piece reads, here cart. The page and the piece share one markup, so they cannot drift apart.
Challenge
MediumServe one row of /tasks/ on its own:
- In
list.html, make the<li>a partial namedtask-row, still drawn for every task. - A view
task_row(request, pk)that renders only that partial, and 404 for a missing task. - The route
"tasks/<int:pk>/row/", namedtask_row.
Press Run, then open /tasks/1/row/: one row.
Try it yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>All tasks</title>
</head>
<body>
<h1>All tasks</h1>
<ul id="tasks">
{% for task in tasks %}
<li id="task-{{ task.id }}">{{ task.title }}{% if task.done %} (done){% endif %}</li>
{% endfor %}
</ul>
</body>
</html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in JSON APIs
Practice on your own: Django playground