Search code examples
pythontemplate-enginemako

How to control EOL and leading spaces in Mako?


With the following, I would like to control the EOL:

<%!
    import sqlite3
    def data():
        return [(1,2,3,4,5), (1,2,3,4,5)]
%>
/**
 * Header file
 */
#define foo bar

% for row in data():
    { \
    % for col in row:
        ${col}, \
    % endfor
    }
% endfor

The goal is to print:

{1,2,3,4,5},
{1,2,3,4,5}    

I've tried to do something like:

% for row in data():
    {<%for i, col in enumerate(row):%>${','*bool(i)}${col}<%endfor%>},
% endfor

Solution

  • How about defining some short functions for the output like so:

    <%!
        def data():
            return [(1,2,3,4,5), (1,2,3,4,5)]
    
        join_data = lambda dat, delim: delim.join(join_row(row) for row in dat)
        join_row = lambda row:'{%s}' % ','.join(str(i) for i in row)
    %>
    

    Then

    ${join_data(data(), ',\n')}
    

    will output

    {1,2,3,4,5},
    {1,2,3,4,5}
    

    or if you want tabbing you could do

        ${join_data(data(), ',\n\t')}
    

    which will yield

        {1,2,3,4,5},
        {1,2,3,4,5}