Template Toolkit, test for the last iteration in a nested loop

I use a toolbox to create a simple JSON response (see code below). I need to put a comma after all the response elements except the last.

I believe that I need to use the TT iterator, but I do not understand. With this code, the comma is still printed at the end of the last element.

The problem is in the section containing

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

this should add a comma if the outer and inner loops are at the last iteration.

Any help regarding my mistake is 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 ~%] ] } 
+4
source share
2 answers

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

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

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

It is also possible to create JSON outside the template itself, but outside the scope of your question.

+5
source

This works for me:

 [% IF loop.last %]}[% ELSE %]},[% END %] 
+6
source

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


All Articles