Login

"Partial Templates" - an alternative to "include"

Author:
vigrid
Posted:
January 29, 2009
Language:
Python
Version:
1.0
Tags:
template tag templates tags partial include partials
Score:
3 (after 5 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. Partial templates, combine with and include by koblas 5 years, 3 months ago
  2. Partial Tag by mnbayazit 5 years ago
  3. partial tag by bl4th3rsk1t3 6 years, 1 month ago
  4. isoutc template filter by japerk 6 years, 3 months ago
  5. Mod to allow simple_tag to access context by leaf 6 years, 10 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.