Jinja PackageLoader raises "unregistered loader type" on Python 3

Viewed 1007

I was playing with around with the jinja basics.

from jinja2 import Environment, PackageLoader, select_autoescape
env = Environment(
    loader=PackageLoader('yourapplication', 'templates'),
    autoescape=select_autoescape(['html', 'xml']
)

Then I do:

template = env.get_template('some_dir_in_templates/mytemplate.html')

which works in Python 2 just fine - I believe this is to be expected since I understand that there are bugs when using with python 3 ... something I fear is the case here.

But when I run the later code in Python 3 I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/dist-packages/jinja2/environment.py", line 830, in get_template
    return self._load_template(name, self.make_globals(globals))
  File "/usr/local/lib/python3.4/dist-packages/jinja2/environment.py", line 804, in _load_template
    template = self.loader.load(self, name, globals)
  File "/usr/local/lib/python3.4/dist-packages/jinja2/loaders.py", line 113, in load
    source, filename, uptodate = self.get_source(environment, name)
  File "/usr/local/lib/python3.4/dist-packages/jinja2/loaders.py", line 234, in get_source
    if not self.provider.has_resource(p):
  File "/usr/local/lib/python3.4/dist-packages/pkg_resources/__init__.py", line 1455, in has_resource
    return self._has(self._fn(self.module_path, resource_name))
  File "/usr/local/lib/python3.4/dist-packages/pkg_resources/__init__.py", line 1505, in _has
    "Can't perform this operation for unregistered loader type"
NotImplementedError: Can't perform this operation for unregistered loader type

Are there any solutions or workarounds in order to fix or make this function in Python 3.4.3?

I am using Jinja 2.9.6

1 Answers

This is a bit of a hack as I hit this myself. I switched to using the Jinja2 FileSystemLoader instead of the PackageLoader on Python 3.

from jinja2 import FileSystemLoader
from my_pkg import templates

templates = Environment(
    loader=FileSystemLoader(templates.__path__[0])
)

This worked for me on Python3. One gotcha/caveat is my_pkg needs the setuptools setup(zip_safe=False, ...). This would decompress the packages and templates from its zipped package so the FileSystemLoader could find them.

Related