Search code examples
pythonjinja2pelican

Trying to override jinja ChoiceReloader in a Pelican Plugin


I have a plugin where I am trying to load a my_assets python package before loading the templates from the folder.

The error I receive is: CRITICAL: No assets environment configured in Jinja2 environment

def foo(generator):
    self._templates = {}
    self._templates_path = []
    self._templates_path.append(os.path.expanduser(os.path.join(self.theme, 'templates')))
    self._templates_path += self.settings['EXTRA_TEMPLATES_PATHS']

    theme_path = os.path.dirname(os.path.abspath(__file__))
    simple_loader = FileSystemLoader(os.path.join(theme_path, "themes", "simple", "templates"))

    self.env = Environment(
        trim_blocks=True,
        lstrip_blocks=True,
        loader=ChoiceLoader([
            PackageLoader('my_assets', 'templates'),
            FileSystemLoader(self._templates_path),
            simple_loader,
            PrefixLoader({'!simple': simple_loader})
            ]),
        extensions=self.settings['JINJA_EXTENSIONS'],
    )
    self.env.filters.update({'strftime': DateFormatter()})
    custom_filters = self.settings['JINJA_FILTERS']
    self.env.filters.update(custom_filters)
def register():
    signals.generator_init.connect(foo)

Solution

  • Found that this was in fact caused by my plugin conflicting with the pelican assets plugin that was using self.env as well. Only needed to override self.env.loader.

    Just ended up using

    self.env.loader = ChoiceLoader([
                PackageLoader('my_assets', 'templates'),
                FileSystemLoader(self._templates_path),
                simple_loader,
                PrefixLoader({'!simple': simple_loader})
                ])