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
If you don't want to do template inheritance, have you considered include
?
{% include 'header.html' %}
Body
{% include 'footer.html' %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With