Hello all
I have heterogenous tree structures that I am rendering with Jinja,
where each node type has its own templates stored in the node class.
Currently I am rendering the content for a node's children separately,
storing intermediate results on a stack, before rendering a template
for the node passing intermediate results explicitly to render.
This works ok, but is a little repetitive and messy. I am wondering if
I could do it more cleanly with recursion within the template. The
small experiment below gives the flavour of what I have in mind. It
seems to work, but is it safe?
--------------------------------------------------------------------------------------------------------
from jinja2 import Template, Environment, BaseLoader,
environmentfilter
import os
@environmentfilter
def render_child(env, child):
return child.render(env.loader)
class Renderer(BaseLoader):
def __init__(self):
self.env = Environment(loader=self)
self.env.filters['render_child'] = render_child
def get_source(self, env, className):
cls = globals()[className]
templSrc = cls.__dict__['template']
return templSrc, className, lambda: True
def render(self, obj):
className = obj.__class__.__name__
template = self.env.get_template(className)
return template.render(this=obj, context=self)
# Nodes for heterogeneous tree
class NodeTypeB(object):
template = 'BBBBBBBB'
def render(self, r):
return r.render(self)
class NodeTypeC(object):
template = 'CCCCCCC'
def render(self, r):
return r.render(self)
class NodeTypeA(object):
template = '''
AAAAAAAAA
{% for c in this.children %}
{{ c | render_child() }} #
render children using filter
{% endfor %}
AAAAAAAAA
'''
def __init__(self):
self.children = [NodeTypeB(), NodeTypeC()]
def render(self, r):
return r.render(self)
r = Renderer()
n = NodeTypeA()
print n.render(r)
--
You received this message because you are subscribed to the Google Groups
"pocoo-libs" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/pocoo-libs?hl=en.