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 me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!