Login

render_partial

Author:
hachaboob
Posted:
September 1, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

Works much like an inclusion_tag but allows the template_name to be given as an argument or defaults to partials/MODELNAME.html where MODELNAME is 'got' from the context object you want to render. Its very rough so improvements very welcome!

It would be nice to be able to pass new context variables as template tag [keyword] arguments for use in the template to be rendered so you basically have a template tag equivalent for render_to_string...

Example usage in a template:

{% render_partial post %} or {% render_partial post partials/super_post.html %}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from django import template

register = template.Library()

class RenderPartialNode(template.Node):
	def __init__(self, object_name, template_name=None):
		self.object_name = object_name
		self.template_name = template_name
	def render(self, context):
		if not self.template_name:
			self.template_name = 'partials/' + context[self.object_name].__class__.__name__.lower() + '.html'
		t = template.loader.get_template(self.template_name)
		return t.render(context)

	
def do_render_partial(parser, token):
	bits = token.split_contents()
	if len(bits) == 2:
		return RenderPartialNode(bits[1])
	elif len(bits) == 3:
		return RenderPartialNode(bits[1], bits[2])
	else:
		raise template.TemplateSyntaxError, "%r requires one or two arguments" % bits[0]

register.tag('render_partial', do_render_partial)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.