SwankyLegg
SwankyLegg

Reputation: 473

Jinja2 Tempates Subdirectory

I'm attempting to organize Jinja2 templates in a way that makes them more manageable. For example, I have a set of team-oriented pages, and a set of prototypes, so my dir structure is:

app > templates > foo_dir > bar.html

In my script that's rendering the templates, I have the following:

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'

How do I access the templates in subdirectories in the most efficient way?

Upvotes: 2

Views: 2327

Answers (1)

mgilson
mgilson

Reputation: 309821

From the documentation on FileSystemLoader, it looks like you can pass a list of directories to be searched (in order). i.e.:

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)

now JINJA_PAGES.get_template will look first in templates_dir for the requested template. If that template isn't found, it will next look in foo_dir.

Upvotes: 2

Related Questions