Reputation: 61
Suppose we have a local python module in the same directory as a mako template: ./my_template.mako ./my_module/module.py
How do I import that module into a Mako template that is supposed to be rendered from the command line using mako-render? The following does not work:
<%! import my_module.module %>
It seems that the local path is not part of the search path. However, putting each custom module into the global path is not an option.
Upvotes: 4
Views: 4037
Reputation: 1
mako-render lives in /usr/local/bin or some path like that.
It is a python script and follows the python interpreter's rules to look for import modules in: 1. its directory (/usr/local/bin) 2. the PYTHONPATH environment variable 3. In the installation libraries.
you can get this working by doing:
$ env PYTHONPATH=. mako-render
Upvotes: 0
Reputation: 1056
My guess is that you are missing the __init__.py
in your ./my_module folder that is required for my_module to be a package. This file can be left empty, it just needs to be present to create the package.
Here is a working example doing what you describe.
Directory Layout
.
├── example.py
├── my_module
│ ├── __init__.py <----- You are probably missing this.
│ └── module.py
└── my_template.mako
Files
example.py
from mako.template import Template
print Template(filename='my_template.mako').render()
my_template.mako
<%! import my_module.module %>
${my_module.module.foo()}
module.py
def foo():
return '42'
__init__.py
# Empty
Running the Example
>> python example.py
42
Upvotes: 6