Search code examples
pythontemplate-enginemako

One-liner for loop output with mako script


Is it possible to populate a mako script's for loop to one line only? All examples I've seen so far create multiple lines and writing the mako for loop in one line causes mako errors.

Example code populating mako template:

data = ['foo', 'bar', 'baz']
template = Template(filename='test.mak')
template.render(data=data)

The template file test.mak (creating multiple lines which is not what I want):

items=
% for d in data:
${d}${'' if loop.last else ','}
% endfor

The expected expanded mako script output should be items=foo,bar,baz.

My current workaround is items=${','.join(data)} as mako script, but I wonder if this is also possible with built-in mako directives.


Solution

  • As mako documentation says you may consume endline character by adding backslash \ at the very end of line. So your template should look like this:

    items=\
    % for d in data:
    ${d}${'' if loop.last else ','}\
    % endfor