【问题标题】:Python lookup functionPython 查找函数
【发布时间】:2011-04-20 00:55:44
【问题描述】:

我想用 mako 设置一个查找功能。在模板之上,我有

<%!
    lookup = { 'key': function }
%>

<%def name="function()">
    Output
</%def>

这样我以后可以使用它

<%def name="body()">
    ${lookup['key']()}
</%def>

这给了我一个函数不是定义的错误。我可以解决这个问题吗?

我知道为什么它不工作,因为它首先运行,在方法被加载之前,但是我该如何设置呢?

【问题讨论】:

    标签: python mako


    【解决方案1】:

    我可以告诉你为什么它不起作用,但我目前没有一个干净的解决方案。你给定的模板编译成这个 Python 代码:

    # -*- encoding:utf-8 -*-
    from mako import runtime, filters, cache
    UNDEFINED = runtime.UNDEFINED
    __M_dict_builtin = dict
    __M_locals_builtin = locals
    _magic_number = 5
    _modified_time = 1285968547.0498569
    _template_filename='<snip>'
    _template_uri='<snip>'
    _template_cache=cache.Cache(__name__, _modified_time)
    _source_encoding='utf-8'
    _exports = ['function']
    
    
    # SOURCE LINE 1
    
    lookup = { 'key': function }
    
    
    def render_body(context,**pageargs):
        context.caller_stack._push_frame()
        try:
            __M_locals = __M_dict_builtin(pageargs=pageargs)
            __M_writer = context.writer()
            # SOURCE LINE 3
            __M_writer(u'\n\n')
            # SOURCE LINE 7
            __M_writer(u'\n')
            return ''
        finally:
            context.caller_stack._pop_frame()
    
    
    def render_function(context):
        context.caller_stack._push_frame()
        try:
            __M_writer = context.writer()
            # SOURCE LINE 5
            __M_writer(u'\n    Output\n')
            return ''
        finally:
            context.caller_stack._pop_frame()
    

    如您所见,您的function 实际上已定义为render_functionThe Mako docs specify how to call defs from outside a template,但它们没有说明如何在运行时正确执行此操作。我链接的代码也只是查找 "render_%s" % name(参见 mako.template,第 217 行),所以您可能考虑这样做。

    【讨论】:

    • 谢谢,我有一个大致的原因,但不确定解决它的最佳方法是,没有一堆 if/switch 流程语句
    【解决方案2】:

    也许您可以将function 的查找从字典创建时间延迟到调用时间?

    <%!
        lookup = { 'key': lambda: function() }
    %>
    

    我没用过 Mako,但它可以在 Python shell 中工作:

    >>> x = lambda: foo()
    >>> x
    <function <lambda> at 0x10047e050>
    >>> x()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in <lambda>
    NameError: global name 'foo' is not defined
    >>> def foo():
    ...    print "Test"
    ... 
    >>> x()
    Test
    

    【讨论】:

    • 不,不错的尝试。我认为在 mako 中它会搜索全局函数,但它不是全局函数。谢谢!
    猜你喜欢
    • 2019-05-29
    • 2011-03-23
    • 2011-08-27
    • 2015-12-02
    • 2021-11-30
    • 1970-01-01
    • 2017-11-22
    • 2021-06-18
    • 2014-04-07
    相关资源
    最近更新 更多