开发者

Multi-part template issue with Jinja2

开发者 https://www.devze.com 2023-01-03 11:22 出处:网络
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).

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' %}
0

精彩评论

暂无评论...
验证码 换一张
取 消