Search code examples
pythonmako

How to duplicate expression specified number of times in one line in Mako


I have this template:

% for n in range(1, max_n + 1):
    ${n}
% endfor

It'll be rendered this way: ( max_n = 3 )

1
2
3

I want these numbers to be in one line, like this:

1 2 3

How can I achieve this in Mako?


Solution

  • In case the template is in a python string you can just escape the newline with \\:

    from mako.template import Template
    
    t = """
    % for n in range(1, max_n + 1):
    ${n} \\
    % endfor
    """
    
    print(Template(t).render(max_n=3))
    >>> 1 2 3