Profile image for Ian Lewis IanLewis
A decorator for creating template tags that get data and place it in the current context
Language
Python
Tags
data django tag template

Data retrieval template tag

1 from django import template 2 3 from community.models import * 4 5 register = template.Library() 6 7 def data_template_tag(data_func, *args, **kwargs): 8 """ 9 A decorator for creating template tags that put data into 10 the template context. 11 12 data_func is a function that returns the data you want to 13 put into the context (normally a queryset). 14 15 Usage: 16 17 @register.tag 18 @data_template_tag 19 def get_my_data(): 20 return MyData.objects.filter(...) 21 22 In the template: 23 24 {% get_my_data as my_data %} 25 26 Arguments are also supported. 27 28 @register.tag 29 @data_template_tag 30 def get_my_data(user): 31 return MyData.objects.filter(user=user) 32 33 {% get_my_data user as my_data %} 34 """ 35 def wrapped(parser, token): 36 bits = list(token.split_contents()) 37 38 args = [] 39 name = None 40 next_as = False 41 for bit in bits[1:]: 42 if bit == "as": 43 next_as = True 44 elif next_as: 45 name = bit 46 break 47 else: 48 args.append(bit) 49 50 if not name: 51 raise TemplateSyntaxError("%r expected format is '%s *args as <name>'" % 52 (bits[0], bits[0])) 53 return DataNode(data_func, args, name) 54 55 #Fix the name so that @register.tag works 56 wrapped.__name__ = data_func.__name__ 57 return wrapped 58 59 class DataNode(template.Node): 60 def __init__(self, data_func, args, var_name): 61 self.data_func = data_func 62 self.args = args 63 self.var_name = var_name 64 65 def __repr__(self): 66 return "<DataNode>" 67 68 def render(self, context): 69 args = [template.resolve_variable(arg, context) for arg in self.args] 70 context[self.var_name] = self.data_func(*args) 71 return u""

Discussion

This tag could be useful for plugging the same data into many pages quickly and easily.

This tag is particularly useful when combined with the cache template tag. The cache template tag can cache the rendered html and if the cache is live the query run by data_func will not be executed.

Comments