Ticket #1065: fragment_caching.py

File fragment_caching.py, 1.2 KB (added by Chris Beaven, 18 years ago)

Ian Maurer's template tag

Line 
1from django.core.template import Library, Node, TemplateSyntaxError,
2resolve_variable
3register = Library()
4
5@register.tag(name="cache")
6def do_cache(parser, token):
7 nodelist = parser.parse(('endcache',))
8
9 parser.delete_first_token()
10
11 args = token.contents.split()
12 if len(args) >= 3:
13 tag_name, expire_time, fragment_name = args[:3]
14 id_names = args[3:]
15 else:
16 raise TemplateSyntaxError("Invalid arguments to cache: %s" % args)
17
18 return CacheNode(nodelist, expire_time, fragment_name, id_names)
19
20class CacheNode(Node):
21 def __init__(self, nodelist, expire_time, fragment_name, id_names):
22 self.nodelist = nodelist
23 self.expire_time = expire_time
24 self.fragment_name = fragment_name
25 self.id_names = id_names
26
27 def render(self, context):
28 cache_id = self.fragment_name
29 for id_name in self.id_names:
30 cache_id += ":%s" % resolve_variable(id_name, context)
31
32 from django.core.cache import cache
33 value = cache.get(cache_id)
34
35 if not value:
36 value = self.nodelist.render(context)
37 cache.set(cache_id, value, float(self.expire_time))
38
39 return value
Back to Top