我该怎么做才能从%def获得返回值?

时间:2013-04-19 20:41:18

标签: mako

如何从%def获得返回值?

makoT1.py:

import mako
from mako.template import Template
from mako.lookup import TemplateLookup
print "Hi world.",
mytemplate = Template(filename='makoT1.mako')
print mytemplate.render(),

makoT1.mako

<%
index = 0
%>
<%def name="a_def(counter)"> Pre: ${counter} <% counter += 1 %> Post: ${counter} <% return counter %> </%def>
index: ${index}
${a_def(index)}
index: ${index}
dalem @ QnD:〜$ python makoT1.py

Hi world. 

index: 0
 Pre: 0  Post: 1 1
index: 0

请注意,上面的第二个“索引”仍为0?这就是我想要解决的问题。我希望它能增加。

makoT1.mako也许是这样的:

<%
index = 0
%>
<%def name="a_def(counter)">
Pre: ${counter} 
<% counter += 1 %> 
Post: ${counter} 
<% return counter %> 
</%def>
index: ${index}
<% index = ${a_def(index)} %>
index: ${index}

但是这给我带来了这个错误:

dalem@QnD:~$ python makoT1.py
Hi world.
Traceback (most recent call last):
  File "makoT1.py", line 5, in <module>
    mytemplate = Template(filename='makoT1.mako')
  File "/usr/local/lib/python2.7/dist-packages/mako/template.py", line 291, in __init__
    module = self._compile_from_file(path, filename)
  File "/usr/local/lib/python2.7/dist-packages/mako/template.py", line 368, in _compile_from_file
    filename)
  File "/usr/local/lib/python2.7/dist-packages/mako/template.py", line 615, in _compile_text
    generate_magic_comment=template.disable_unicode)
  File "/usr/local/lib/python2.7/dist-packages/mako/template.py", line 597, in _compile
    node = lexer.parse()
  File "/usr/local/lib/python2.7/dist-packages/mako/lexer.py", line 241, in parse
    if self.match_python_block():
  File "/usr/local/lib/python2.7/dist-packages/mako/lexer.py", line 376, in match_python_block
    match.group(1)=='!', lineno=line, pos=pos)
  File "/usr/local/lib/python2.7/dist-packages/mako/lexer.py", line 131, in append_node
    node = nodecls(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/mako/parsetree.py", line 139, in __init__
    self.code = ast.PythonCode(text, **self.exception_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/mako/ast.py", line 37, in __init__
    expr = pyparser.parse(code.lstrip(), "exec", **exception_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/mako/pyparser.py", line 60, in parse
    ), **exception_kwargs)
mako.exceptions.SyntaxException: (SyntaxError) invalid syntax (<unknown>, line 1) (u'index = ${a_def(index)} \n') in file 'makoT1.mako' at line: 11 char: 1

对我来说,当第11行正常工作时,第11行会得到SyntaxError似乎很奇怪:

<% index = 0 %>

$ {a_def(index)}不应该从a_def(计数器)返回整数吗?

1 个答案:

答案 0 :(得分:1)

使用

<% index = a_def(index) %>

不要使用

<% index = ${a_def(index)} %>

<% index = ${capture(a_def(index))} %>