Skip to main content

a tag for improving django template fragment cache

Project description

Django Fragment Cache

Django provides template fragment caching, such as :

{% load cache %}
{% cache 500 sidebar %}
    .. sidebar ..
{% endcache %}

But the variable sidebar still to be passed to the template every time, otherwise the fragment is blank when the cache expires.

If the data acquisition process is time consuming, then the fragment cache is to exist in name only.

So, this module provides another way to use the template cache.

How to use?


pip install django-fragment-cache

Install Requires:

  • django >= 2

edit your to add fragment_cache to your NSTALLED_APPS.



you need provide a callable object to tell module how to get data, and the function return a dict.

only call function when cache expires.

import time
def get_data(num=10):
    return {'nums': list(range(num))}

def test(request):
    return render(request, 'test.html', {'get_data': get_data})

The {% fragment_cache %} template tag is similar to {% cache %} , for example:

{% load fragment_cache %}
{% fragment_cache 500 get_data %}
        {% for i in nums %}
            <li> {{ i }}</li>
        {% endfor %}
{% endfragment_cache %}

Sometimes, you might want to cache multiple copies of a fragment depending on some dynamic data that appears inside the fragment.

This allows different parameters to be cached to cache different results, for example:

{% load fragment_cache %}
{% fragment_cache 500 get_data 6 %}
        {% for i in nums %}
            <li> {{ i }}</li>
        {% endfor %}
{% endfragment_cache %}

Enjoy yourself.

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for django-fragment-cache, version 0.5.1
Filename, size File type Python version Upload date Hashes
Filename, size django_fragment_cache-0.5.1-py3-none-any.whl (3.7 kB) File type Wheel Python version py3 Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page