Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Toolkit, test for last iteration in a nested loop

I'm using template toolkit to form a simple JSON response (see the code below). I need to put a comma after all elements of the response except the last.

I believe I need to make use of TTs iterator, however I'm not getting it right.
With this code, a comma is still printed on the end of the last element.

The problem lies with the section that contains

[% UNLESS outer.last && loop.last %],[% END %]

this should add a comma unless the outer and inner loops are on their last iteration.

Any help on what I'm getting wrong greatly appreciated.

{ "success": true, "filesdata": [
[%~ USE outer = iterator(objects); FOREACH object IN outer;
    FOREACH rep IN object.reps;
        IF rep.rep == reptype %]
{ "id":"[% object.id | xml %]", "url":"[% rep.src | xml %]", "story":"[% object.story | xml %]" }[% UNLESS outer.last && loop.last %],[% END %]
        [%~ END;
    END;
END ~%]
] }
like image 865
mark Avatar asked Nov 01 '12 21:11

mark


2 Answers

This works for me:

[% IF loop.last %]}[% ELSE %]},[% END %]
like image 146
Twistar Avatar answered Nov 15 '22 16:11

Twistar


Have you tried using the join vmethod? You can create a list and join it with a comma:

[% items.join(', ') %]

Having said that, you may also want to look at Template::Plugin::SimpleJson. You could create a hash and then pass it to this plugin. However you do decide to do it, you probably don't want to worry about quoting your JSON in the actual template file and using something like this could save you some heartache down the line.

There's also the option of creating the JSON outside of the template itself, but that's outside the scope of your question.

like image 32
oalders Avatar answered Nov 15 '22 15:11

oalders