You can also cache template fragments using the cache tag. Add {% load cache%} near the top of the template to notify the template to access the cache tag.
The template label {% Cache%} caches the contents of the block within a given time. It requires at least two parameters: the cache time-out (in seconds) and the name of the specified cache fragment. Example:
{% Load cache%} {% Cache Sidebar%} .. Sidebar. {% Endcache%}
Sometimes you might want to cache multiple copies of dynamic content based on fragments. For example, you want to cache the sidebar separately for each user of the previous example. This only needs to pass additional parameters to {% cache%} to identify the cache fragment.
{% Load cache%} {% Cache sidebar request.user.username%} .. Sidebar for logged in User: {% Endcache%}
It is also possible to pass more than one parameter. Simply pass the parameter to {% cache%}.
The cache timeout can be used as a template variable as long as it resolves to an integer value. For example, if the template variable my_timeout value is 600, then the following two examples are equivalent.
{% cache Sidebar%} ... {% Endcache%} {% Cache my_timeout Sidebar%} ... {% Endcache%}
This feature is useful in avoiding template duplication. You can save the timeout time in a variable and reuse it elsewhere.