访问 Mako 命名空间中定义的变量

发布于 2024-11-19 20:31:16 字数 460 浏览 2 评论 0原文

通常,在 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

在我的用例中,somevarfoo 是相关的。如果我还能够从导入模板中访问 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北城孤痞 2024-11-26 20:31:16

我遇到了同样的问题 - 答案在有关继承的文档中:

命名空间对象的 attr 访问器允许访问模板中声明的模块级变量。通过访问 self.attr,您可以访问继承链中的常规属性,如 <%! %>部分。

因此我认为你想要 base.attr.somevar

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.

猫腻 2024-11-26 20:31:16

正如用户 9000 上面所建议的,我找到了一种方法来做到这一点。我将其发布,以便将其记录下来,以防其他人需要它,但我仍然希望具有更多专业知识的人可以提供更好的方法。

据我所知,您无法通过命名空间访问模块块中定义的函数,但您可以访问 <%def>。默认情况下 <%def> 块会直接转储到上下文缓冲区,因此您必须进行一些扭曲:

## base.mako
<%!
  somevar = ["one", "two", "three"]
%>

<%def name="getSomeVar()">
  <%
    return somevar
  %>
</%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:

## 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文