开发者

Calling a def as a function in a Mako template

开发者 https://www.devze.com 2023-02-06 06:50 出处:网络
I\'d like to use a def as a function, and call it from an if开发者_C百科 block: <%def name=\"check(foo)\">

I'd like to use a def as a function, and call it from an if开发者_C百科 block:

<%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

Needless to say, this syntax does not work. I don't want to just do an expression substitution (and just render the output of the def) as the logic is consistent, but the content rendered differs from place to place.

Is there a way to do this?

Edit: Enclosing the logic in the def in <% %> seems to be the way to go.


Just define the whole function in plain Python:

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

Or you could just define the function in Python and pass it to the context.


Yes, using plain Python syntax in the def works:

<%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>

If anyone knows a better way, I'd love to hear it.

0

精彩评论

暂无评论...
验证码 换一张
取 消