Performance: Template fragment caching
Improves page load speed by caching parts of the HTML template to avoid repeated rendering.
Jump into concepts and practice - no test required
{% load cache %}
{% cache 600 sidebar_cache_key %}
<div>{% include 'sidebar.html' %}</div>
{% endcache %}{% load cache %}
<div>{% include 'sidebar.html' %}</div>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No caching, full template render | N/A (server-side) | N/A | N/A | [X] Bad |
| Template fragment caching enabled | N/A (server-side) | N/A | N/A | [✓] Good |
{% cache %} in Django templates?{% cache %} tag{% cache %} tag is used to wrap parts of a template that should be cached for faster page loads.{% cache timeout key %} where timeout is an integer and key is a string.300 as timeout and 'sidebar' as key in correct order and quotes.{% cache 600 'menu' user.id %}
user.id changes?user.id changes, Django creates a new cache entry for that user, so the fragment is cached separately.{% cache 'sidebar' 300 %}
Sidebar content
{% endcache %}'sidebar' first and 300 second, which is reversed.