from django.template import Library, Node, loader, resolve_variable, \ TemplateSyntaxError from django.template.context import Context register = Library() class PartialTemplateNode(Node): """ Partial template templatetag to pass simple parameters formatted like: {% partial_template template_name:template_name param1:variable1 param2:variable2 param4:"True" param5:22 %} Based on other two django snippets: http://www.djangosnippets.org/snippets/297/ http://www.djangosnippets.org/snippets/1302/ """ def __init__(self, template_name, params): self.template_name = template_name self.params = params def render(self, context): for k,v in self.params.items(): if v[0] == '\"' or v[0] == '\'': try: # Trying to evaluate the python code in quotes (like "True") self.params[k] = eval(v[1:-1]) continue except: pass self.params[k] = resolve_variable(v, context) template = loader.get_template('%s' % (self.template_name,)) template_context = Context(self.params) return template.render(template_context) @register.tag def partial_template(parser, token): items = token.split_contents() if len(items)<3: raise TemplateSyntaxError('Missing template tag arguments. '\ 'At least 2 arguments needed') template_name = items[1] parameters = {} for item in items[2:]: param, value = item.split(':') param = param.strip() value = value.strip() parameters[param] = value return PartialTemplateNode(template_name, parameters)