4

我想使用 adef作为函数,并从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 in 中<% %>似乎是要走的路。

4

2 回答 2

7

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

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

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

于 2011-01-20T16:39:14.757 回答
2

是的,在 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>

如果有人知道更好的方法,我很想听听。

于 2011-01-20T16:20:55.443 回答