"Partial Templates" - an alternative to "include"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from django.template import Library, Node, Variable, loader
from django.template.context import Context

register = Library()


class PartialTemplateNode(Node):
	def __init__(self, template_name, context_item):
		self.template_name = template_name
		self.context_item = Variable(context_item)

	def render(self, context):
		template = loader.get_template('partials/%s.html' % (self.template_name,))
		item = self.context_item.resolve(context)
		template_context = Context({
			'item': item
		})
		return template.render(template_context)

@register.tag
def partial_template(parser, token):
	tag, template_name, context_item = token.split_contents()
	return PartialTemplateNode(template_name, context_item)

Comments

bcurtu (on January 30, 2009):

Great idea. Thanks

#

dwsBeta2 (on January 31, 2009):

I like it, but would rather have "partials/" come from a setting, so that I could use "_" instead. (Keeping partials in the same directory with the templates they're used in is one less place to look.)

#

(Forgotten your password?)