Can we loop through items in a list layout?

I feel like I’ve seen this done before. In a list layout having a for loop to loop over the items of the module. Is that possible? If so, what’s the syntax (example)?

Yep, first you configure the component tag to use object: "collection":

{% component source: "Portfolio Items", layout: "Collection List", object: "collection", type: "module" %}

Then in the list layout you do a forloop on this.items:

{% for item in this.items %}
    {{item.name}} etc...
{% endfor %}

I’ve found this is actually a much better way of rendering lists and tend to do this all the time now as it make the list view and wrapper totally contained in the layout module, rather then having extra wrapper code on the page around the component tag.

TIP: When I do this, I name my List Layout something like “Collection List” so I know that layout is using this method.

Weird I tried that first. I must have done something wrong. I’ll try again.

I’m sure I even saw this in an example you provided previously. Thanks @Adam.Wilson as always you’ve come through with the right answer.

(edit: Just realized that if you didn’t watch Flight of the Conchords that gif might come off as really creepy. It’s from this if you haven’t seen it.)

Hey @Adam.Wilson I know I posted this a while ago. A little clarification, I tried using this.name etc inside my loop and that didn’t work. It did however work when I switched to item.name. Are you able to grab your data with this.fieldname inside a for loop on a list layout?

No, because this refers to the entire object/collection of items.
That’s why we redefine this.items as item (or whatever tag you like) and that becomes our reference in the loop.

You could directly reference an item without looping (or within a loop) by using it’s index:
{{this.items[0].name}}
(0 being the item’s index)
But this is usually impractical.

And just to clarify this is when rendering the list layout as object: "collection"


(edit: Just realized that if you didn’t watch Flight of the Conchords that gif might come off as really creepy. It’s from this if you haven’t seen it.)

Ha ha, yes I’ve seen Flight of the Conchords… love it!

Thanks @Adam.Wilson. Wow. I must really have been tired yesterday. I swear I read {{this.name}} inside your for loop. Clearly I didn’t.