4

I'd like to use a def as a function, and call it from an if 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.

Hollister
  • 3,758
  • 2
  • 20
  • 22

2 Answers2

7

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.

Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
  • Ok, but is there any advantage over Python in a mako def? – Hollister Jan 20 '11 at 16:56
  • @Hollister: Well, Mako defs have too many cool features to list here (`self.caller, self.body` etc, read a Mako tutorial), but when you don't use any of them you might as well go with the simpler Python syntax. – Jochen Ritzel Jan 20 '11 at 17:10
  • Am I right in thinking this does not allow for overriding `check` function down the inheritance tree whereas defining `check` as a `%def` with body in plain Python makes it possible to both call it as a normal Python function and to override it? – Piotr Dobrogost Aug 22 '14 at 13:35
2

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.

Hollister
  • 3,758
  • 2
  • 20
  • 22