2

如何从 %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(counter) 返回整数吗?

4

1 回答 1

1

利用

<% index = a_def(index) %>

不要使用

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

或者

<% index = ${capture(a_def(index))} %>
于 2013-04-20T04:41:22.153 回答