Templates

Django Template Language

Use Django's template language for rendering dynamic content. Avoid embedding business logic in templates; keep templates focused on presentation.

Example:

<!-- users/list.html -->
{% extends 'base.html' %}
{% block content %}
  <h1>User List</h1>
  <ul>
    {% for user in users %}
      <li>{{ user.name }} ({{ user.email }})</li>
    {% endfor %}
  </ul>
{% endblock %}

Template Organization

  • Store templates in app-specific folders (e.g., templates/app_name/).
  • Use a global templates/ directory for shared layouts and components.
  • Name templates clearly by feature or purpose.

Template Inheritance

  • Use {% extends %} and {% block %} for layout inheritance and reusable sections.
  • Create a base template (e.g., base.html) for common structure (header, footer, navigation).

Example:

<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
  <title>{% block title %}My App{% endblock %}</title>
</head>
<body>
  <header>...</header>
  <main>
    {% block content %}{% endblock %}
  </main>
  <footer>...</footer>
</body>
</html>

Best Practices

  • Avoid logic-heavy templates; use context data from views.
  • Escape all output ({{ variable }}) to prevent XSS.
  • Use template tags and filters for formatting and presentation.
  • Organize templates for maintainability and reusability.
  • Document template structure for new team members.