4

I want to loop over a list and print the elements seperated by ',', with no trailing comma. I can't just ', '.join(headings) because of the formating and escaping. But the following obviously leaves me with a trailing comma.

% for x in headings:
  <a href='#${x|u}'>${x}</a>, \
% endfor

Or more generally: When iterating over something in a Mako template, is there a way to know if I reached the last element (or first, or nt)?

Brutus
  • 7,139
  • 7
  • 36
  • 41

3 Answers3

4

I do stuff like this:

<%def name="format( item )"><a href="#${item|u}">${item|u}</a>
</%def>

${', '.join( format(item) for item in l)}
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
  • Any Idea how to call the build-in formats such as HTML escaping (`|u`, etc.) from your own functions? – Brutus Feb 01 '10 at 17:06
4

To keep track of the first or last leg through the loop, in Mako like in plain Python, use:

% for i, x in enumerate(headings): 

so i is 0 on the first leg and len(headings) - 1 on the last leg.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
3

Extending on @AlexMartelli's answer, I like to couple the enumerate thing with a nice trick to keep the instruction small:

% for i, x in enumerate(xs):
  ${','*bool(i)} ${x}
% endfor
Jo So
  • 25,005
  • 6
  • 42
  • 59