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
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
andloop.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