我想使用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中的逻辑包含在内似乎是要走的路。
答案 0 :(得分:5)
只需在plain Python中定义整个功能:
<%!
def check(foo):
return not foo
%>
%if check([]):
works
%endif
或者你可以在Python中定义函数并将其传递给上下文。
答案 1 :(得分: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>
如果有人知道更好的方式,我很乐意听到。