stripping last comma from python genshi for loop

108 Views Asked by At

I am using python genshi NewTexTemplate to generate code. Some of the code blocks are comma separated, so for the following code template for instance:

{% for item in data.items %}
{ 
   // fill template here 
     print item

}, 
{% end %}

and having items = [1,2,3], this would yield:

{
 1
},
{
 2
},
{
 3
}, 

I'd like to remove the last comma. Is there a way to detect the last iteration in a for loop in genshi? I check the documentation, but there doesn't seem to be any.

PS: I can actually send a data structure which has a flag to tell if the current iteration is the last one, but I am exploring if genshi has something built in for that.

1

There are 1 best solutions below

0
Matheus Portela On BEST ANSWER

Quick and dirty fix that should work:

{% for i in range(data.items) %}
    { 
    print data.items[i]
    {% choose i %}
        {% when len(data.items) - 1 %}}{% end %}
        {% otherwise %}},{% end %}
    {% end %}
{% end %}