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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With