访问 Mako 命名空间中定义的变量
通常,在 Mako 中“导入”命名空间似乎只允许访问 def。
## base.mako
<%
somevar = ["one", "two", "three"]
%>
<%def name="foo()">Bar</%def>
还有一个导入模板:
## child.mako
<%namespace name="base" file="base.mako" />
${base.foo()} # works
${base.somevar} # fails: no soup for you
在我的用例中,somevar
和 foo
是相关的。如果我还能够从导入模板中访问 somevar
,这对我来说会很方便。这样做的最佳实践是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我遇到了同样的问题 - 答案在有关继承的文档中:
因此我认为你想要
base.attr.somevar
。I've had the same problem - the answer is in the documentation on inheritance:
Thus you want
base.attr.somevar
I think.正如用户 9000 上面所建议的,我找到了一种方法来做到这一点。我将其发布,以便将其记录下来,以防其他人需要它,但我仍然希望具有更多专业知识的人可以提供更好的方法。
据我所知,您无法通过命名空间访问模块块中定义的函数,但您可以访问
<%def>
。默认情况下<%def>
块会直接转储到上下文缓冲区,因此您必须进行一些扭曲:然后从另一个模板将 base.mako 命名空间导入为
base
并访问${base.getSomeVar()}
获取somevar
的值。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:Then from another template import the base.mako namespace as
base
and access${base.getSomeVar()}
to get the value ofsomevar
.