Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I import a local module in a Mako template?

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.

like image 635
user1722901 Avatar asked Sep 21 '25 02:09

user1722901


1 Answers

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
like image 162
Kenneth E. Bellock Avatar answered Sep 22 '25 17:09

Kenneth E. Bellock