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 name %} and {% endpartialdef %}; with the word inline it is also drawn in place, once for each item 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 the new /tasks/ page alone.
- In
tasks/list.html, make the<li>in the loop aninlinepartial namedtask-row, so/tasks/still draws every row. - In
tasks/views.py, addtask_row(request, pk): render only that partial, passingtask, or Django's 404 page. - In
tasks/urls.py, add"tasks/<int:pk>/row/"namedtask_row.
Open /tasks/3/row/: only Call the bank (done), no heading.
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