Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access variables defined in Mako namespace

Tags:

python

mako

Normally, "importing" a namespace in Mako appears 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?

like image 681
sink Avatar asked Dec 21 '25 06:12

sink


2 Answers

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.

like image 134
cdyson37 Avatar answered Dec 22 '25 18:12

cdyson37


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.

like image 34
sink Avatar answered Dec 22 '25 18:12

sink



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!