10

I'm working on creating my first cookiecutter. By and large, this has gone well, but I now want to add a jinja2 filter of my own.

In line with the comments in this issue, I've created a new Jinja2 extension much like the one here. Full code for this extension is here:

https://github.com/seclinch/sigchiproceedings-cookiecutter/commit/5a314fa7207fa8ab7b4024564cec8bb1e1629cad#diff-f4acf470acf9ef37395ef389c12f8613

However, the following simple example demonstrates the same error:

# -*- coding: utf-8 -*-
from jinja2.ext import Extension


def slug(value):
    return value


class PaperTitleExtension(Extension):
    def __init__(self, environment):
        super(PaperTitleExtension, self).__init__(environment)
        environment.filters['slug'] = slug

I've dropped this code into a new jinja2_extensions directory and added a simple __init__.py as follows:

# -*- coding: utf-8 -*-
from paper_title import PaperTitleExtension

__all__ = ['PaperTitleExtension']

Based on this piece of documentation I've also added the following to my `cookiecutter.json' file:

"_extensions": ["jinja2_extensions.PaperTitleExtension"]

However, running this generates the following error:

$ cookiecutter sigchiproceedings-cookiecutter
Unable to load extension: No module named 'jinja2_extensions'

I'm guessing that I'm missing some step here, can anyone help?

Saff
  • 501
  • 3
  • 13

3 Answers3

2

Had the same issue, try executing with python3 -m option

My extension in extensions/json_loads.py

import json

from jinja2.ext import Extension


def json_loads(value):
    return json.loads(value)


class JsonLoadsExtension(Extension):
    def __init__(self, environment):
        super(JsonLoadsExtension, self).__init__(environment)
        environment.filters['json_loads'] = json_loads

cookiecutter.json

{
  "service_name": "test",
  "service_slug": "{{ cookiecutter.service_name.replace('-', '_') }}",
...
  "_extensions": ["extensions.json_loads.JsonLoadsExtension"]
}

Then I executed with python3 -m cookiecutter . no_input=True timestamp="123" extra_dict="{\"features\": [\"redis\", \"grpc_client\"]}" -f and it works fine.

onesiumus
  • 279
  • 6
  • 26
0

I ran into a similar error earlier.

Unable to load extension: No module named 'cookiecutter_repo_extensions'

The problem was that in my case there was a dependency to the 'cookiecutter-repo-extension' which I had not installed in my Virtual Environment.

0

The directory containing your extension needs to be on your PYTHONPATH.

https://github.com/cookiecutter/cookiecutter/issues/1211#issuecomment-522226155

A PR to improve the docs would be appreciated ✍️

michaeljoseph
  • 7,023
  • 5
  • 26
  • 27