Jinja2 的多部分模板问题
创建模板时,我通常有 3 个独立的部分(页眉、正文、页脚),我将它们组合起来将单个字符串传递到 Web 服务器(在本例中为 CherryPy)。
我的第一个方法如下...
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
但这包含重复的代码,所以我的下一个方法是...
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)
但是,这意味着每个部分都是在自己的环境中创建的 - 这会是一个问题吗?这种方法还有其他缺点吗?
我选择了三部分方法而不是子模板方法,因为我认为它可能更灵活(并且更容易遵循),但我可能是错的。有人想说服我使用页眉、正文和页脚块可能会更好吗?
任何建议将不胜感激。 艾伦
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你不想做模板继承,你有没有考虑过
include
?If you don't want to do template inheritance, have you considered
include
?