Last Item in Loop Processing

56 views
Skip to first unread message

Nathan Ward

unread,
Jun 2, 2018, 8:51:51 AM6/2/18
to Pebble Templating Engine
How can I detect the last item in a list is a for tag?

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

Bastien Jansen

unread,
Oct 14, 2018, 4:58:44 PM10/14/18
to Pebble Templating Engine
The loop variable has first and last fields which can be used to do what you want, see https://github.com/PebbleTemplates/pebble/wiki/for.
Reply all
Reply to author
Forward
0 new messages