python - Jinja2 的多部分模板问题

标签 python templates jinja2

在创建模板时,我通常有 3 个独立的部分(页眉、正文、页脚),我将它们组合起来以将单个字符串传递给网络服务器(在本例中为 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)

但是,这意味着每个部分都是在其自己的环境中创建的 - 这会成为问题吗?这种方法还有其他缺点吗?

我选择了 3 部分方法而不是子模板方法,因为我认为它可能更灵活(也更容易遵循),但我可能错了。有人想说服我使用页眉、正文和页脚 block 可能会更好吗?

如有任何建议,我们将不胜感激。 艾伦

最佳答案

如果不想做模板继承,有没有考虑过include

{% include 'header.html' %}
    Body
{% include 'footer.html' %}

关于python - Jinja2 的多部分模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3052702/

相关文章:

c++ - 定义一个模板类但是得到 'is not a class template'

python - 提高Python中 `compute_optimal_weights`函数的性能

python - 使用 AUTH=NTLM 针对 Exchange imap 服务器验证 imaplib.IMAP4_SSL

python - 我可以将 with 语句与 MySQLdb.Connection 对象一起使用吗?

c++ - 奇怪的是重复出现的模板模式。没有匹配的函数用于调用..模板参数/替换失败

c++ - invoke_result_t<> 没有将 lambda 与引用参数匹配

python - Django 1.11 : What fails `pickle` in my parallel test run?

python - url_for 包含在 jinja2 中

python - 如何检查变量是否是神社中的字典

python - 值错误: too many values to unpack (expected 2) in flash in Flask