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 e开发者_如何学Goasier 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' %}
精彩评论