Login

"Partial Templates" - an alternative to "include"

Author:
vigrid
Posted:
January 29, 2009
Language:
Python
Version:
1.0
Score:
4 (after 6 ratings)

This snippet adds simple partial support to your templates. You can pass data to the partial, and use it as you would in a regular template. It is different from Django's {% include %}, because it allows you to pass a custom variable (context), instead of reusing the same context for the included template. This decouples the templates from each other and allows for their greater reuse.

The attached code needs to go into templatetags folder underneath your project. The usage is pretty simple - {% load ... %} the tag library, and use {% partial_template template-name data %} in your template. This will result in template passed as template-name to be loaded from partials folder. The .html extension will be appended to the file name. The file has to be in one of template paths accessible to the loader) and rendered with data as its context. The data is available in the template as an item context variable.

You can find more information in the relevant Django documentation

 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)

More like this

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

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.)

#

Please login first before commenting.