Login

Conditional template parsing block

Author:
mk
Posted:
April 29, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

I'm developing a regionalization extension based on PostGIS and GeoDjango for a web-based LCA software. Because PostGIS (or PostgreSQL) is not available everywhere, we needed a way to fully disable the geographic extensions.

Because of that, I set out to create a template block tag which only gets evaluated when GIS support is active and totally ignored (treated as a comment) otherwise.

I had some problems getting my BoringNode to work (which should just pass the content through), so I've just used the AutoEscapeControlNode (why? Because it was the first usable class that jumped into my eye.) for this purpose.

 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
from django.conf import settings
from django.template import Node, Library
from django.template.defaulttags import CommentNode, AutoEscapeControlNode

register = Library()

def BoringNode(Node):
	def __init__(self, nodelist):
		self.nodelist = nodelist

	def render(self, context):
		return self.nodelist.render(context)

@register.tag
def gisblock(parser, token):
	if not settings.BRIGHTWAY_GIS_SUPPORT:
		parser.skip_past('endgisblock')
		return CommentNode()

	nodelist = parser.parse(('endgisblock',))
	parser.delete_first_token()

	# HACK!!! why doesn't BoringNode work? I always get strange
	# errors ('NoneType' has no attribute 'source')
	return AutoEscapeControlNode(True, nodelist)
	#return BoringNode(nodelist)

More like this

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

Comments

Please login first before commenting.