I currently have templates in multiple different sub directories and I would like to load all of the templates in jinja2. It appears that just pointing the FileSystemLoader directory at the top of the tree doesn't pick up anything in the sub folders.
Is there a way to get jinja2 to load all of the sub directories (just a single level down is ok but the whole tree would be preferable)?
So far I've managed to do this with a choice loader:
sub_dirs = [os.path.join(template_file_root,dirname) for dirname in os.listdir(template_file_root)
\ if os.path.isdir(os.path.join(template_file_root, dirname))]
jinja_dirs = [ jinja2.FileSystemLoader(dirname) for dirname in sub_dirs ]
template_env = jinja2.Environment (loader = jinja2.ChoiceLoader(jinja_dirs))
However this seems a little hacky. Any better suggestions?
Jinja does take the subfolders into account, but templates must be referenced with paths relative to the root folder.
If we have mydir/foo/bar.html, this works:
template_env = jinja2.Environment(loader=jinja2.FileSystemLoader('mydir'))
template_env.get_template('foo/bar.html')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With