Jinja2 filesystemloader loads all subdirectories

Currently, I have templates in several different subdirectories, and I would like to load all the templates in jinja2. It seems that just specifying the FileSystemLoader directory at the top of the tree does not pick up anything in the subfolders.

Is there a way to get jinja2 to load all the subdirectories (only one level down is ok, but the whole tree is preferable)?

So far, I have managed to do this with the select 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 bit hacked. Any best deals?

+4
source share
1 answer

Jinja takes into account subfolders, but templates must refer to 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') 
+17
source

Source: https://habr.com/ru/post/1400660/


All Articles