Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 filesystemloader load all subdirectories

Tags:

python

jinja2

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?

like image 365
chrisst Avatar asked Mar 09 '12 21:03

chrisst


1 Answers

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')
like image 160
jd. Avatar answered Nov 11 '22 18:11

jd.