【问题标题】:Static includes in nested namespaces using Mako使用 Mako 将静态包含在嵌套命名空间中
【发布时间】:2014-10-16 11:21:15
【问题描述】:

我正在尝试 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>

这只是一个例子,但我希望它足以描述我的问题。

【问题讨论】:

    标签: pyramid mako


    【解决方案1】:

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

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

    迭代这个字典的值将提供一个Namespace 每次使用 &lt;%namespace&gt; 标签时的对象,在任何地方 继承链。

    您的继承链仅由 child.mako 和 base.mako 组成。在这些唯一的 child.mako 中声明了命名空间 (rb),因此这是 context.namespaces 中唯一的命名空间。如果在% for ns in context.namespaces.values(): 行之后插入${ns.uri},您可以轻松看到这一点。这将在输出中单独呈现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
    

    但是从我所看到的并且不知道为什么它不起作用。

    【讨论】:

    • 是的,我已经尝试过您发布的代码,但似乎ns.context.namespaces 提供了与context.namespaces.values 相同的命名空间。
    猜你喜欢
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 2019-08-03
    • 2019-06-20
    • 2015-07-21
    • 2011-02-08
    相关资源
    最近更新 更多