How to track state during iteration in Python Mako Templates

I want to iterate over the list and print the elements separated by the ',' character, without a comma. I can’t just ', '.join(headings)because of the formation and shielding. But the following obviously leaves me with a trailing comma.

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

Or in the general case: when repeating something in a Mako template, is there a way to find out if I reached the last element (or the first or nt)?

+3
source share
3 answers

I do like this:

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

${', '.join( format(item) for item in l)}
+4
source

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

% for i, x in enumerate(headings): 

i 0 len(headings) - 1 .

+4

@AlexMartelli, enumerate , :

% for i, x in enumerate(xs):
  ${','*bool(i)} ${x}
% endfor
+2
source

Source: https://habr.com/ru/post/1730690/


All Articles