Package: django-viewlet
Render template parts with extended cache control.InstallationInstall django-viewlet in your python environment$pipinstalldjango-viewletSupportsDjangoversions 1.3 - 2.0 andPythonversions 2.6 - 3.6.ConfigurationAddviewletto yourINSTALLED_APPSsetting so Django can find the template tagINSTALLED_APPS=(...'viewlet',)Jinja2If you’re usingJinja2as your template engine for Django versions < 1.8,
put this in your Django settings:VIEWLET_TEMPLATE_ENGINE='jinja2'If you’re usingCoffinorJingo, add theViewletExtensionto their settings,
and optionally switch to their respective environment.Coffin:JINJA2_EXTENSIONS=(...'viewlet.loaders.jinja2_loader.ViewletExtension',)VIEWLET_JINJA2_ENVIRONMENT='coffin.common.env'Jingo:JINJA_CONFIG={'extensions':(...'viewlet.loaders.jinja2_loader.ViewletExtension',),}VIEWLET_JINJA2_ENVIRONMENT='jingo.get_env'Django 1.8+:AddViewletExtensionto the list of extensions of Jinja2 template engineTEMPLATES=[{'BACKEND':'django.template.backends.jinja2.Jinja2',# ...'OPTIONS':{# ...'extensions':[# ...'viewlet.loaders.jinja2_loader.ViewletExtension',],}}],UsageA viewlet is almost like a function based django view, taking a template context
as first argument instead of request.
Place your viewlets inviewlets.pyor existingviews.pyin your django app directory.fromdjango.template.loaderimportrender_to_stringfromviewletimportviewlet@viewletdefhello_user(context,name):returnrender_to_string('hello_user.html',{'name':name})You can then render the viewlet with theviewlettemplate tag:{% load viewlets %}<p>{% viewlet hello_user request.user.username %}</p>… and in your Jinja2 templates:<p>{% viewlet 'host_sponsors', host.id) %}</p>Specifying cache backendBy default viewlet will try usingviewletcache alias, falling back todefault. You can specify
which alias should be used in settings:VIEWLET_DEFAULT_CACHE_ALIAS='template_cache'CACHES={# ...'template_cache':{# ...},# ...}Additionally, you can override cache alias in viewlet decorator withusingargument@viewlet(using='super_cache')defhello_user(context,name):returnrender_to_string('hello_user.html',{'name':name})Refreshing viewletsA cached viewlet can be re-rendered and updated behind the scenes withviewlet.refreshimportviewletviewlet.refresh('hello_user','monkey')# orhello_user.refresh('monkey')The decorator@viewlet(name,template,key,timeout)nameOptional reference name for the viewlet, defaults to function name.templateOptional path to template. If specified the viewlet must return a context dict,
otherwise it is responsible to return the rendered output itself.keyOptional cache key, if not specified a dynamic key will be generatedviewlet:name(args...)timeoutCache timeout. Defaults to configured cache backend default timeout, None = eternal, 0 = uncached.ExamplesThe content returned by the viewlet will by default be cached. Use thetimeoutargument to change this.@viewlet(timeout=30*60)defhello_user(context,name):returnrender_to_string('hello_user.html',{'name':name})Tip:SettimeouttoNoneto cache forever and useviewlet.refreshto update the cache.Django viewlet will by default build a cache keyviewlet:name(args...).
To customize this key pass a string to the viewlet decorator argumentkeythat includes string mod operators for each
viewlet argument.@viewlet(timeout=30*60,key='some_cache_key_%s')defhello_user(context,name):returnrender_to_string('hello_user.html',{'name':name})Django viewlet will cache returned context instead of html by using thetemplatedecorator argument.
This is useful if cached html is too heavy, or your viewlet template needs to be rendered on every call.
The specified template will then be rendered with the viewlet context merged with the parent context, usually aRequestContext.@viewlet(template='hello_user.html',timeout=30*60)defhello_user(context,name):return{'name':name}Note:Return context dict for the template, not rendered html/textIf there is no need for caching, set the viewlet decorator argumenttimeoutto 0.@viewlet(timeout=0)defhello_user(context,name):returnrender_to_string('hello_user.html',{'name':name})By default your viewlets will be named as the function. To override this you can set the decorator argumentname@viewlet(name='greeting')defhello_user(context,name):returnrender_to_string('hello_user.html',{'name':name})A powerful usage ofviewlet.refreshis to use it together with Django signals:classProduct(Model):name=CharField(max_length=255)@viewlet(timeout=None)defproduct_teaser(context,id):product=get_context_object(Product,id,context)returnrender_to_string('product_teaser.html',locals())defrefresh_product_teaser(instance,**kwargs):viewlet.refresh('product_teaser',instance.id)post_save.connect(refresh_product_teaser,Product)Viewlets can also be accesses with AJAX by addingviewlet.urlsto your Django root urls:urlpatterns=patterns('',(r'^viewlet/',include('viewlet.urls')),)The url ends with the viewlet name followed by a querystring used askwargsto the viewlet:http://localhost:8000/viewlet/[name]/?arg=1…