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

问题描述 投票:2回答:2

我想使用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

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

有没有办法做到这一点?

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

python mako function
2个回答
5
投票

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

<%!
def check(foo):
    return not foo
%>
%if check([]):
    works
%endif

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


1
投票

是的,在def工作中使用普通的Python语法:

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

    return False
  %>
</%def>

如果有人知道更好的方式,我很乐意听到它。

© www.soinside.com 2019 - 2024. All rights reserved.