[Twisted-web] fragments with child lookup

Markus Schiltknecht markus at bluegap.ch
Fri Sep 22 02:32:47 CDT 2006


I've now solved my problem, sort of. I'm still wondering, if there is a 
more elegant solution, probably integrated into nevow. Since, IMHO, this 
is one of the use-cases of a template system.

I did more or less the following (simplified, naming could be improved, 

class Container(rend.Page):
	addSlash = True

	def __init__(self, source):
		self.source = source
		self.docFactory = self.source.getFactory();

	def locateChild(self, ctx, segments):
		""" Loads sub-pages (fragments?) for all the remaining
		    segments. It does its own lookup with the
		    childFragmentLookup() method.
		    All children are then added to the slot 'children'
		    in reversed ordering, so I can simply pop()
		children = []

		child = self
		while len(segments) > 0:
			if segments[0] != '':
				child = child.childFragmentFactory(segments[0])
				if child is None:
					return appserver.NotFound


			segments = segments[1:]

		ctx.fillSlots('children', children)
		curr_counter = len(children)
		return self, ()

	def childFragmentFactory(self, name):
		""" Tries to create a child for a given name. May return
		    None! (This should probably better raise an
		    exception, no?)
		child_source = self.source.getChild(name)
		if child_source is not None:
			return Container(child_source)

	def render_content(self, ctx, data):
		""" every fragment may have a 'content' renderer, where
		    it's child fragment should be included. This looks
		    up the next child and returns it for rendering.
		children = ctx.locateSlotData('children')
		if len(children) > 0:
			child = children.pop()
			curr_counter = len(children)
			return child
			raise Exception("content renderer called too many times!")

The children have to be stored in the context. I've also tried returning 
  the child in the Container.locateChild() method, and then hook the 
renderHTTP() method to render the parents first. But I've had no luck 
with fetching the parents from the context (and it's parent contexts). I 
would prefer that, because I wouldn't have to write my own childLookup() 

Thoughts? Comments?



More information about the Twisted-web mailing list