Jinja2 模板子目录

2 投票
1 回答
2061 浏览
提问于 2025-04-18 08:04

我正在尝试以更易管理的方式组织Jinja2模板。比如说,我有一组与团队相关的页面,还有一组原型,所以我的文件夹结构是:

app > templates > foo_dir > bar.html

在我的脚本中,用来渲染这些模板的部分是这样的:

templates_dir = os.path.join(os.path.dirname(__file__), 'templates')
JINJA_PAGES = jinja2.Environment(
  loader=jinja2.FileSystemLoader(templates_dir),
  extensions=['jinja2.ext.autoescape'],
  autoescape=True)


class Page(webapp2.RequestHandler):

  category = None
  template = category + None
  url = None

  def get(self):
    template = JINJA_PAGES.get_template(self.template)
    rendered = template.render(self.TemplateArgs())
    self.response.write(rendered)

  def TemplateArgs(self):
    return {}


class FooPage(Page):

  category = 'page_category'
  template = templates_subdir + 'template_name'
  url = '/foo'

我该如何以最有效的方式访问子文件夹中的模板呢?

1 个回答

2

根据关于 FileSystemLoader 的文档,看来你可以传递一个目录列表,让程序按顺序去查找这些目录。也就是说:

templates_dir = os.path.join(os.path.dirname(__file__), 'templates')
foo_dir = os.path.join(templates_dir, 'foo_dir')
JINJA_PAGES = jinja2.Environment(
    loader=jinja2.FileSystemLoader([templates_dir, foo_dir]),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

现在 JINJA_PAGES.get_template 会首先在 templates_dir 这个目录里查找你请求的模板。如果在这个目录里找不到,它就会接着在 foo_dir 里查找。

撰写回答