首页 > 解决方案 > 从父文件夹获取模板部分

问题描述

我的项目分为许多模块。

每个模块都有自己的/templates文件夹,其中包含自己的相关模板文件。

这些模板文件中有一些通用组件(标题,导航),我希望将它们提取到“部分”中,然后将其包含在每个模块的模板文件中(即:{% include 'nav.html' %}

问题

如何以允许模块的模板文件进入shared包含这些部分的文件夹的方式设置我的模板环境?

我当前的环境设置

template_dir = os.path.join(os.path.dirname(__file__), 'views')
env = jinja2.Environment(
    loader=jinja2.FileSystemLoader(template_dir), 
    autoescape=True)

self.render('some_template.html', env=env)   # render function

此当前配置仅允许我进入/templates每个模块中的文件夹。但是,模板文件(在/templates目录内)也应该可以访问每个模块目录之外的部分文件。

理想情况下,应用程序目录应如下所示:

app/
  shared/
    header.html <-- templates within modules need to access these
    nav.html
  modules/
    module_a/
      handler.py
      templates/
        my_template.html  <-- needs access to partials from 'shared/' 
    module_b/
    module_c/

标签: jinja2

解决方案


推荐阅读