Search code examples
pythontemplatesmako

How do you pass an array to a mako template?


I want to pass an array of strings to Mako's render method but this doesn't work:

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

Solution

  • Within a '%' line, you're writing regular Python code that doesn't need the escaping:

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