如何将数组传递给 mako 模板?

问题描述

我想将字符串数组传递给 Mako 的 render 方法,但这不起作用:

from mako.template import Template

mytemplate = Template(filename="some.template")
str = mytemplate.render(first="John",last="Smith",nicknames=[
                        "JJ","Johnny","Jon"])
print(str)

some.template =

Hello ${first} ${last}
Your nicknames are:
% for n in ${nicknames}:
${n}
% endfor

解决方法

在“%”行中,您正在编写不需要转义的常规 Python 代码:

% for n in nicknames:
${n}
% endfor