Access variables defined in Mako namespace
Normally, "importing" a namespace in Mako appear开发者_如何学JAVAs to only allow access to defs.
## base.mako
<%
somevar = ["one", "two", "three"]
%>
<%def name="foo()">Bar</%def>
And an importing template:
## child.mako
<%namespace name="base" file="base.mako" />
${base.foo()} # works
${base.somevar} # fails: no soup for you
In my use case somevar
and foo
are related. It would be convenient for me to also be able to access somevar
from within the importing template. What is the best practice for doing this?
I've had the same problem - the answer is in the documentation on inheritance:
The attr accessor of the Namespace object allows access to module level variables declared in a template. By accessing self.attr, you can access regular attributes from the inheritance chain as declared in <%! %> sections.
Thus you want base.attr.somevar
I think.
As user 9000 suggests above, I figured out one way to do it. I'm posting it so it is documented in case somebody else needs it but I still hope somebody with more expertise can chip in with a better way.
As far as I can tell you can't access functions defined in a module block through the namespace, but you can access a <%def>
. By default <%def>
blocks dump straight to the context buffer so you have to do some contortions:
## base.mako
<%!
somevar = ["one", "two", "three"]
%>
<%def name="getSomeVar()">
<%
return somevar
%>
</%def>
Then from another template import the base.mako namespace as base
and access${base.getSomeVar()}
to get the value of somevar
.
精彩评论