Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-part template issue with Jinja2

When creating templates I typically have 3 separate parts (header, body, footer) which I combine to pass a single 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

like image 459
Alan Harris-Reid Avatar asked Dec 22 '22 02:12

Alan Harris-Reid


1 Answers

If you don't want to do template inheritance, have you considered include?

{% include 'header.html' %}
    Body
{% include 'footer.html' %}
like image 190
Ryan Ginstrom Avatar answered Dec 26 '22 11:12

Ryan Ginstrom