Django

Django Templates

Template inheritance and i18n hooks

Django Templates

Templates separate HTML from Python. TaskBoard uses a base layout and section blocks.

Base template

<!-- templates/base.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <title>{% block title %}TaskBoard{% endblock %}</title>
</head>
<body>
  {% if messages %}
    <ul>{% for m in messages %}<li>{{ m }}</li>{% endfor %}</ul>
  {% endif %}
  {% block content %}{% endblock %}
</body>
</html>

Task list

{% extends "base.html" %}
{% block content %}
<h1>{% translate "Open tasks" %}</h1>
<ul>
  {% for task in tasks %}
    <li><a href="{% url 'tasks:task-detail' task.pk %}">{{ task.title }}</a>
      ({{ task.project.name }})</li>
  {% empty %}
    <p>No open tasks.</p>
  {% endfor %}
</ul>
{% endblock %}

CSRF in forms

<form method="post" action="{% url 'tasks:task-toggle' task.pk %}">
  {% csrf_token %}
  <button type="submit">Toggle done</button>
</form>