Python 在Mako模板中将def作为函数调用
我想使用Python 在Mako模板中将def作为函数调用,python,mako,function,Python,Mako,Function,我想使用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
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
%如果len(foo.things)==0:
返回错误
%其他:
%对于foo.things中的thing:
%如果thing.status==“活动”:
返回真值
%恩迪夫
%结束
%恩迪夫
返回错误
%如果检查(c.foo):
#呈现一些内容
%其他:
#呈现一些其他内容
%恩迪夫
不用说,这种语法不起作用。由于逻辑是一致的,我不想只进行表达式替换(并只渲染def的输出),但渲染的内容因地而异
有办法做到这一点吗
编辑:
将逻辑封装在
中的def中似乎是一种方法。是的,在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>
如果有人知道更好的方法,我很想听听。只需在以下内容中定义整个函数:
%如果选中([]):
作品
%恩迪夫
或者您可以用Python定义函数并将其传递给上下文。好的,但是mako def比Python有什么优势吗?@Hollister:好的,mako defs有太多很酷的特性,这里无法列出(
self.caller,self.body
等,请阅读mako教程),但是当你不使用任何一个函数时,你最好使用更简单的Python语法。我认为这不允许覆盖继承树下的check
函数,而将check
定义为%def
并使用纯Python的body,这样就可以将其作为普通Python函数调用要推翻它吗?
<%!
def check(foo):
return not foo
%>
%if check([]):
works
%endif