On Mon, Aug 6, 2012 at 7:27 AM, Andreas <[email protected]> wrote:
>  But jinja does not like enumerate either? There must be a smart way of
> doing this?

Jinja2 has special "loop" variables
(http://jinja.pocoo.org/docs/templates/#for), for example loop.index
to get the current iteration of the loop, and loop.last to tell if
this is the last iteration of the loop. So, you can do this:

>>> jinja2.Template("{% for x in xs %}{{x}}{% if not loop.last %},{% endif %}{% 
>>> endfor %}").render(xs=[10,20,30,40])
u'10,20,30,40'

Or, if you wanted to use enumerate, you can pass it into the template:

>>> jinja2.Template("{% for i,x in enumerate(xs) %}{{ (i,x) }} {% endfor 
>>> %}").render(xs=[10,20,30,40], enumerate=enumerate)
u'(0, 10) (1, 20) (2, 30) (3, 40) '

Or you could just write a function that does what you need, and pass
that function into the template:

>>> join_with_commas = lambda xs: ", ".join(str(x) for x in xs)
>>> jinja2.Template("{{ join_with_commas(xs) }}").render(xs=[10,20,30,40], 
>>> join_with_commas=join_with_commas)
u'10, 20, 30, 40'

And finally, the best solution would be to just use the builtin "join" filter!

>>> jinja2.Template("{{ xs | join(', ') }}").render(xs=[10,20,30,40])
u'10, 20, 30, 40'

http://jinja.pocoo.org/docs/templates/#join

-steve

-- 
You received this message because you are subscribed to the Google Groups 
"pocoo-libs" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/pocoo-libs?hl=en.

Reply via email to