Static包含在使用Mako的嵌套命名空间中

时间:2014-08-22 14:48:11

标签: pyramid mako

我正在尝试this method向我的命名空间添加静态包含但我面临的问题是,嵌套命名空间中的静态包含不包含在基本模板中。为了使问题更具体,我在下面发布一些示例代码:

base.mako

<!DOCTYPE html>
<head>
    % for ns in context.namespaces.values():
        % if hasattr(ns, 'includes'):
    ${ns.includes()}
        % endif
    % endfor
</head>
<body>
    ${next.body()}
</body>
</html>

child.mako

<%inherit file="base.mako"/>
<%namespace name="rb" file="buttons.mako"/>
${rb.render_buttons}

buttons.mako

<%namespace name="lib" file="lib.mako"/>

<%def name="includes()">
<script type="text/javascript" src="${request.static_url('project:static/lib.js')}"></script>
</%def>
<%def name="render_buttons()>
    <button onclick="some_function_from_lib_js()">Click me!</button>
    ${lib.render_text()}
</%def>

lib.mako

<%def name="includes()">
<script type="text/javascript" src="${request.static_url('project:static/other.js')}"></script>
</%def>
<%def name="render_text()">
    <button onclick="some_function_from_other_js()">No! Click me!</button>
</%def>

这只是一个例子,但我希望能够描述我的问题。

1 个答案:

答案 0 :(得分:0)

您发布的代码中存在语法错误。此外,还有对外部(例如request)实体的引用。请始终确保您的代码正确无误并且在发布之前有效。

问题似乎是context.namespaces是继承链模板中声明的名称空间的集合。这可以从文档中的以下statement推断出来:

  

迭代此词典的值将提供Namespace   每次使用<%namespace>标记时的对象,在任何地方   继承链。

您的继承链仅包含child.mako和base.mako。其中只有child.mako声明了名称空间(rb),因此这是context.namespaces中唯一的名称空间。如果您在${ns.uri}行之后插入% for ns in context.namespaces.values():,则可以轻松查看此内容。这将在输出中单独呈现buttons.mako字符串。

您的案例中的解决方案是不仅在继承链中的模板中声明的名称空间中查找includes defs,而且还查找由这些名称空间声明的名称空间中的% for ns in context.namespaces.values(): % for ns2 in ns.context.namespaces.values(): % if hasattr(ns2, 'includes'): ${ns2.includes()} % endif % endfor % if hasattr(ns, 'includes'): ${ns.includes()} % endif % endfor defs。像

这样的东西
{{1}}

然而,从我所看到的情况来看,它并不起作用,也不知道为什么。

相关问题