4

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

言うまでもなく、この構文は機能しません。ロジックは一貫しているため、式の置換だけを行う (そして定義の出力をレンダリングするだけ) ことはしたくありませんが、レンダリングされるコンテンツは場所によって異なります。

これを行う方法はありますか?

編集: ロジックを def で囲むの<% %>が良いようです。

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 に答える