Jinja2 downloads templates from a separate location than the working directory

I have a module that handles the creation and execution of SQL queries using Jinja2 to render templates. The module itself and the directory called "templates" are located on a network drive, which I can access from several computers on the network.

Everything works when I work from the same directory, as expected.

When I try to download and use this module from a separate place, I get a TemplateNotFound: error. The function itself looks like this: line containing the highlighted error:

 from jinja2 import Environment, FileSystemLoader, Template, meta def get_sql_query(position): filename = "PositionDelta.sqltemplate" # Create Jinja2 Environment, using the 'templates' folder Error here --> env = Environment(loader=FileSystemLoader('templates')) template = env.get_template(filename) # Get Source of template file template_source = env.loader.get_source(env, filename)[0] # Parse template source and get all undeclared variables parsed_content = env.parse(template_source) template_variables = list(meta.find_undeclared_variables(parsed_content)) # Get all tag values associated with position tag_values = get_tags_list(position) # Combine template variables and tag values into dictionary and render sql query from template dictionary = dict(zip(template_variables, tag_values)) sql_query = template.render(dictionary) return sql_query 

This faulty function is the following line:

 env = Environment(loader=FileSystemLoader('templates')) 

I think when I call the FileSystemLoader function, it looks for the template folder relative to the working folder. How can I set it to search for a template directory relative to the module location itself?

+5
source share
2 answers

In the end, the method I was looking for requires creating my module (s) in a package. I decided to use the Jinja2 package loader method because it searches for template files relative to the package itself, and not relative to the working directory:

 import jinja2 templateEnv = jinja2.Environment( loader=jinja2.PackageLoader('package_name', 'templates')) template = templateEnv.get_template( 'template_filename' ) template.render({'var1':var1, 'var2':var2}) 
+2
source

This works for me:

 from jinja2 import Environment, FileSystemLoader template_dir = '/home/colin/template_dir' env = Environment(loader=FileSystemLoader(template_dir)) 

My guess is that since your path does not start with a forward slash of it loading relative to your application. Try using the full path to the template directory.

+3
source

All Articles