Multi-part template issue with Jinja2

Posted by Alan Harris-Reid on Stack Overflow See other posts from Stack Overflow or by Alan Harris-Reid
Published on 2010-06-16T11:09:57Z Indexed on 2010/06/16 11:12 UTC
Read the original article Hit count: 334

Filed under:
|
|

Hi,

When creating templates I typically have 3 separate parts (header, body, footer) which I combine to pass a singe string to the web-server (CherryPy in this case).

My first approach is as follows...

from jinja2 import Environment, FileSystemLoader
env  = Environment(loader=FileSystemLoader(''))

tmpl = env.get_template('Body.html')
page_body = tmpl.render()

tmpl = env.get_template('Header.html')
page_header = tmpl.render()

tmpl = env.get_template('Footer.html')
page_footer = tmpl.render()

page_code = page_header + page_body + page_footer

but this contains repetitious code, so my next approach is...

def render_template(html_file):
    from jinja2 import Environment, FileSystemLoader
    env  = Environment(loader=FileSystemLoader(''))
    tmpl = env.get_template(html_file)
    return tmpl.render()

page_header = render_template('Header.html')
page_body   = render_template('Body.html')
page_footer = render_template('Footer.html)

However, this means that each part is created in its own environment - can that be a problem? Are there any other downsides to this approach?

I have chosen the 3-part approach over the child-template approach because I think it may be more flexible (and easier to follow), but I might be wrong. Anyone like to convince me that using header, body and footer blocks might be better?

Any advice would be appreciated. Alan

© Stack Overflow or respective owner

Related posts about python

Related posts about templates