This article mainly introduces the template fragment cache in the Python Django framework, including passing parameters to the cache tag. If you need it, you can refer to the cache tag to cache the template fragment. Add {% load cache %} near the top of the template to notify the template to access the cache tag.
The template tag {% cache %} caches the block content within the specified time. It requires at least two parameters: the cache timeout (in seconds) and the name of the specified cache segment. Example:
{% Load cache %} {% cache 500 sidebar %}... sidebar... {% endcache %}
Sometimes you may want to cache multiple copies of Dynamic Content Based on fragments. For example, you want to cache the sidebar for each user in the previous example. In this way, you only need to pass extra parameters to {% cache %} to identify the cache segment.
{% Load cache %} {% cache 500 sidebar request. user. username %}... sidebar for logged in user... {% endcache %}
It is also feasible to pass more than one parameter. Simply pass the parameter to {% cache % }.
The cache timeout value can be used as a template variable as long as it can be resolved to an integer. For example, if the template variable my_timeout is 600, the following two examples are equivalent.
{% Cache 600 sidebar %}... {% endcache %} {% cache my_timeout sidebar %}... {% endcache %}
This feature is useful in avoiding duplicate templates. You can save the timeout time in the variable and reuse it elsewhere.