I'm working on a Pyramid project and am considering something which will come later. My particular use case is ascending the resource tree to construct a breadcrumb, but I'm curious about the general implementation, too.
In Python code, I'd be wanting this:
while resource is not None:
pass # do something with resource
resource = resource.__parent__
But in Chameleon, you only get tal:repeat
, which is a for
loop. I can perceive that you could write a function which would be provided to the template:
def ascend(resource):
while resource is not None:
yield resource
resource = resource.__parent__
This could then be used as tal:repeat="item ascend(resource)"
.
This might be generalised to a while loop thusly:
def while_(value, condition, suite):
while condition(value):
yield value
value = suite(value)
Usage: tal:repeat="item while_(resource, lambda resource: resource is not None, lambda resource: resource.__parent__)"
. Ugly. I think you'd fairly quickly go to specialising!
Similarly, if break
were supported, an infinite for
loop would do. But it isn't. (Nor would it be wise to support it, I think.
Is there any nicer or easier way of achieving this? (The general case or my specific case.)
No, there isn't.
Chameleon templates are not meant to implement complex logic; the original Zope Page Template philosophy is to leave all the business logic up to Python code, and the template has just enough power to turn the information generated into a presentation, and nothing more.
This is why Chameleon doesn't give you anything more than a for loop; it's not the responsibility of the template to traverse complex structures, its responsibility is limited to creating a representation of already-processed data.