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 ~%]
] }
This works for me:
[% IF loop.last %]}[% ELSE %]},[% END %]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With