[Mako] Making "import" work intuitively in a mako template text.

256 views
Skip to first unread message

Aaron Watters

unread,
May 19, 2010, 2:21:37 PM5/19/10
to Mako Templates for Python
I embedded Mako in WHIFF
(http://whiffdoc.appspot.com/docs/W1100_1075.MakoGrading)
and it works very nicely, as long as it doesn't try to do a
relative module import.

In particular when I include a Mako template
in a WHIFF directory I would like relative
imports in the embedded Python code to
import any code file that matches in the same directory.
For example here is a fragment of a Mako
template (from an embedding in a WHIFF template)
in the directory ~/whiff/test/misc/
...
<%
# inlined python to summarize text
import shaney
text = text.strip()
if text:
do something using shaney....
else:
do something else....
%>

Here the "import shaney" I think should import
the ~/whiff/test/misc/shaney.py module in the same directory as the
template file, but instead I get an ImportError:

/Users/Aaron/work/whiff/test/root/memory:0x106b590 in
render_body(context=<mako.runtime.Context object at 0x114ef70>,
**pageargs={})
<type 'exceptions.ImportError'>: ./misc/summarize.whiff :: No module
named shaney

I haven't tested it outside of WHIFF, but this may happen
inside WHIFF because the template is passed many levels
down before it gets processed in the WHIFF configuration.

Is there any reasonable way to get the import to work
the way I expect it to work? (I don't think modifying sys.path
for this special purpose is very reasonable.) Somehow I need
to tell the evaluator "pretend you are living in this directory: a/b/
c"
so it finds the right file/module to import...

Let me know what you suggest, or any other comments.

Thanks! -- Aaron Watters
===
$ man less
less is more


--
You received this message because you are subscribed to the Google Groups "Mako Templates for Python" group.
To post to this group, send email to mako-d...@googlegroups.com.
To unsubscribe from this group, send email to mako-discuss...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mako-discuss?hl=en.

Michael Bayer

unread,
May 19, 2010, 2:47:58 PM5/19/10
to mako-d...@googlegroups.com
here are your options:

1. make sure things are actually laid out that way, i.e.:

foo/bar/misc/
__init__.py
shaney.py
mytemplate.mako
mytemplate.py

2. override __import__ to do whatever path munging is required (Myghty used to do this). Details at http://docs.python.org/library/functions.html#__import__

3. use "import hooks". I've never heard of these before but they seem to be referenced by #2's link. This might be the way to go. You can place whatever preamble you like in all templates using the "imports" flag on Template, TemplateLookup.

4. use a preprocessor on your templates that changes "import" statements to read some other way. this is probably unnecessary.
Reply all
Reply to author
Forward
0 new messages