Created
July 19, 2011 17:53
-
-
Save ddgromit/1093257 to your computer and use it in GitHub Desktop.
Django Template Tag to Render Partial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Source: http://freeasinbeard.org/post/107743420/render-partial-in-django | |
# Author: Martin Häger | |
from django import template | |
register = template.Library() | |
class PartialNode(template.Node): | |
def __init__(self, partial, params): | |
self.partial = partial | |
self.params = params | |
def render(self, context): | |
context_params = {} | |
for k, v in self.params.items(): | |
try: | |
context_params[k] = eval(v) | |
except: | |
context_params[k] = template.Variable(v).resolve(context) | |
t = template.loader.get_template('partials/%s' % self.partial) | |
return t.render(template.Context(context_params)) | |
@register.tag | |
def render_partial(parser, token): | |
parts = token.split_contents() | |
params = {} | |
try: | |
tag_name, partial = parts[:2] | |
if partial.startswith('"'): partial = partial[1:-1] | |
for p in parts[2:]: | |
k, v = p.split(':',1) | |
params[k] = v | |
except ValueError: | |
raise template.TemplateSyntaxError, '%r tag requires at least a single argument and no ' \ | |
'spaces in name:value list' % parts[0] | |
return PartialNode(partial, params) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fix a bug in the original where if there was a colon in the value of one of the passed in variables, it would throw an error because the param split would split into more than two components.