How can I detect the last item in a for loop in a Pebble Template?

2k Views Asked by At

How can I detect the last item in a list in a for loop in a Pebble Template (http://www.mitchellbosecke.com/pebble/home)?

I am using Pebble to generate JSON. I have a list of objects that I need to iterate over and I need to include a comma after each one except for the last one.

Here's the relevant template code where I tired to use the loop.index and loop.length in an IF statement., but it doesn't work (I'd need to check for loop.length -1 anyway).

Template:

"menu": {
    "items": {
    {% for menuItem in menuItems %}
    "{{ menuItem.name }}": "{{ menuItem.value }}"{%- if loop.index < loop.length %},{% endif %}
    {%- endfor %}
    }
}

Example desired Output:

"menu": {
    "items": {
         "item1": "Item 1",
         "item2": "Item 2
    }
}

I've used the Jinja2 Python template engine before, which has a syntax similar to Pebble. Jinja2 also has an index.last property that is a boolean and can be used in an IF statement like this. I don't know of anything similar in Pebble.

Nathan

2

There are 2 best solutions below

2
On

First of all, I think you should check out dedicated JSON libraries like Jackson or GSON. It may be more adapted to what you are tying to do.

That said, I ran into the same problem and the latest version includes in the loop the properties loop.first loop.last and loop.revindex.

I found it in the following test.

https://github.com/PebbleTemplates/pebble/blob/11dd4783d44afbeb269c9d98cf9579aad0e53394/pebble/src/test/java/com/mitchellbosecke/pebble/CoreTagsTest.java#L177

1
On

While inside of the loop, Pebble provides a couple of special variables to help you out:

  • loop.index: a zero-based index that increments with every iteration.
  • loop.length: the size of the object we are iterating over.
  • loop.first: True if first iteration
  • loop.last: True if last iteration
  • loop.revindex: The number of iterations from the end of the loop

Documentation is updated with missing variables here

https://github.com/PebbleTemplates/pebble/wiki/for