Template fragment caching helps speed up your website by saving parts of a page so they don't have to be rebuilt every time.
0
0
Template fragment caching in Django
Introduction
When a part of your webpage takes a long time to generate but doesn't change often.
When you want to reduce the load on your server by reusing saved HTML snippets.
When you have a sidebar or menu that stays the same for many users.
When you want to improve page load speed without caching the whole page.
When you want to cache only specific sections like a list of popular articles.
Syntax
Django
{% cache <timeout_in_seconds> <cache_key> %}
... template code to cache ...
{% endcache %}<timeout_in_seconds> is how long the cached content stays saved.
<cache_key> is a unique name for the cached part.
Examples
This caches the sidebar for 10 minutes (600 seconds).
Django
{% cache 600 sidebar %}
<div>Sidebar content here</div>
{% endcache %}This caches a user profile section for 5 minutes, using the user's ID to create a unique cache key.
Django
{% cache 300 user_profile user.id %}
<p>User: {{ user.username }}</p>
{% endcache %}Sample Program
This template caches the greeting message for 2 minutes. The current time below it updates every time the page loads, showing the difference between cached and dynamic content.
Django
{% load cache %}
<html lang="en">
<head><title>Fragment Cache Example</title></head>
<body>
<h1>Welcome to my site</h1>
{% cache 120 greeting %}
<p>Hello, this message is cached for 2 minutes.</p>
{% endcache %}
<p>Current time: {{ now }}</p>
</body>
</html>OutputSuccess
Important Notes
Make sure caching is enabled in your Django settings for fragment caching to work.
Use unique cache keys to avoid mixing cached content from different parts of your site.
Remember that cached content will not update until the timeout expires or the cache is cleared.
Summary
Template fragment caching saves parts of a page to speed up loading.
Use the {% cache %} tag with a timeout and a unique key.
It helps when only some parts of a page are slow or rarely change.