Caching Parsed Django Templates
Standard Django rendering parses a template every time it is rendered. Storing the parsed template can be a nice little speed up for your Django site. This code snippet does a great job of doing that for all templates. One drawback to this approach though is that the server needs restarted whenever a template changes. I’ve taken a slightly different approach to this where I create a separate method for caching and rendering templates. I only call this when rendering several templates in a view and the speed up is absolutely necessary. Some places you might consider doing this is when sending out bulk emails or when rendering a long list of objects and each object uses the same template.
First create a file called template.py in your application. Then we create a method that will cache a template when called and return the rendered template.
from django.template import Context, loader
template_cache = {}
def render_cached(template_name, dictionary=None):
global template_cache
t = template_cache.get(template_name, None)
if not t or settings.DEBUG:
template_cache[template_name] = t = loader.get_template(template_name)
dictionary = dictionary or {}
context_instance = Context(dictionary)
return t.render(context_instance)
This method takes two arguments the template name and a dictionary to use for the template context. It first gets the template out of the cache. It then looks if the template was retrieved or if your debug setting is on. If either of these cases exist, it uses the base django loader to retrieve the parsed template and store it in the cache dictionary. Then we create a context instance for the dictionary and return the rendered code.
To be able to use the method you just import and call it.
from template import render_cached
html = render_cached("sometemplate.html", {})


