Login

partial tag

Author:
bl4th3rsk1t3
Posted:
June 1, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

This is another partial tag, taken from a previous partial tag.

The previous one assumed template locations by hardcoding in "partials/%s", etc. I took all that out, and made it work. And I took out the not needed third parameter for passing in your own data

So now you call like this:

{% partial "partials/mypartial.html" %}

It passes the template context var into the partial, so anything you do in the main template, will work in the partial

Just make sure you've got all the right imports.

 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def split_contents2(token):
	"""
	Is an updated way of splitting contents for a token,
	it does the split, but fixes the list.. 
	EX:
	From a tag call like this: {% partial "partials/template.html" %}
	usually it's like: ['partial','"partials/template.html"'] (notice the " double quotes)
	fixes it with: ['partial','partials/template.html'] (takes out the " quotes)
	"""
	value=token.split_contents()
	newvalues=[]
	for val in value:
		if (type(val)==types.UnicodeType or isinstance(val,str)) and val[0]=='"' and val[-1]=='"':
			val=re.sub(r'^\"','',val)
			val=re.sub(r'\"$','',val)
		newvalues.append(val)
	return newvalues

class PartialTemplateNode(Node):
	"""
	Node renderer for partial tag
	"""
	def __init__(self,template):
		self.template=template
	def render(self,context):
		template=loader.get_template(self.template)
		if context: return template.render(context)
		else: return template.render()

@register.tag
def partial(parser,token):
	"""
	Renders partials
	EX:
	{% load tags %}
	{% partial template-name %}
	"""
	tag,template_name=split_contents2(token)
	if not template_name: raise template.TemplateSyntaxError, "the 'partial' tag needs a template to render"
	return PartialTemplateNode(template_name)

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, 8 months ago

Comments

carljm (on June 2, 2009):

Maybe I'm dense, but I don't understand how this is any different from the built-in "include" tag.

#

Please login first before commenting.