将def作为Mako模板中的函数调用

Hol*_*ter 3 python function mako

我想使用a def作为函数,并从if块中调用它:

<%def name="check(foo)">
    % if len(foo.things) == 0:
        return False
    % else:
        % for thing in foo.things:
            % if thing.status == 'active':
                return True
            % endif
        % endfor
    % endif
    return False
</%def>

% if check(c.foo):
    # render some content
% else:
    # render some other content
% endif
Run Code Online (Sandbox Code Playgroud)

不用说,这种语法不起作用.我不想只是做一个表达式替换(并且只是渲染def的输出),因为逻辑是一致的,但渲染的内容因地而异.

有没有办法做到这一点?

编辑: 在def中包含逻辑<% %>似乎是要走的路.

Joc*_*zel 5

只需在纯Python中定义整个函数:

<%!
def check(foo):
    return not foo
%>
%if check([]):
    works
%endif
Run Code Online (Sandbox Code Playgroud)

或者您可以在Python中定义函数并将其传递给上下文.