Challenge 2: Cache a Template Fragment — Possible Solution
====================================================================
{% load cache %}
Welcome, {{ request.user.username }}!
{% cache 300 book_list_fragment %}
{% for book in books %}
- {{ book.title }} — ${{ book.price }}
{% endfor %}
{% endcache %}
WHY THIS WORKS
--------------
- {% load cache %} must appear before {% cache %} can be used in a
template — it loads the tag library that provides the cache-related
template tags.
- The welcome heading references {{ request.user.username }} OUTSIDE the
{% cache %}/{% endcache %} block specifically so it is NEVER cached —
if it were placed inside the cached block, every visitor within the
5-minute cache window would see whichever user's name happened to be
logged in when the fragment was first rendered and cached, which would
be a real (and confusing) bug.
- {% cache 300 book_list_fragment %} caches everything between it and
{% endcache %} for 300 seconds (5 minutes) under the fragment name
"book_list_fragment" — the book list itself is the expensive-to-render,
identical-for-everyone part of the page, making it a good candidate for
fragment caching, while the personalized greeting above it is not.
- This demonstrates the core value of fragment caching over
@cache_page: a single page can mix content that's safe to cache (the
book list) with content that must never be cached (anything
user-specific), without needing to split them into separate views.