Menu

Templates

Introduction

Django's template engine lets you generate HTML dynamically. Templates support variables, filters, tags, and template inheritance for DRY (Don't Repeat Yourself) design.

Template basics

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

<!-- post_list.html -->
{% extends 'base.html' %}

{% block title %}Blog Posts{% endblock %}

{% block content %}
  <h1>Blog Posts</h1>
  {% for post in posts %}
    <article>
      <h2><a href="{% url 'post_detail' post.pk %}">{{ post.title }}</a></h2>
      <p>{{ post.body|truncatewords:30 }}</p>
      <small>{{ post.created_at|date:"F j, Y" }}</small>
    </article>
  {% empty %}
    <p>No posts yet.</p>
  {% endfor %}
{% endblock %}

Assignment

  1. Create a base template with navigation and footer.
  2. Create list and detail templates for your blog posts.
  3. Use template tags and filters to format dates and truncate text.

Support Us!

SaneGenius is a project by a team of passionate software engineers giving back to the community. Join us in empowering learners around the globe by supporting SaneGenius!