Somehow the following code produces an error. I’ve searched a lot to come to an answer, but can’t find it anywhere. So I’m guessing I’m doing something that isn’t possible
If I run the code without the foreach loop, then it works. But I need the foreach loop
Any thoughts?
<?php $events = $page; ?>
<?php foreach($events as $event): ?>
What are you trying to accomplish? I think you’re confusing some elements, because right now you’re looping over the $page object, while I think you’re trying to loop over some events.
On which page are these events situated? I assume you will need something like this
I don’t know what OPs event situation is, it could be children pages but it could also be a custom field in his yaml (like the calender plugin does it)
Oh I just saw you already mentioned that, and I did forget the ->structure() call anyway good catch, edited my first reply to reflect this correction
@dreadnip Yes I would like to loop once over the $page object. But somehow that doesn’t happen.
I have to say, I’m using this loop for other purposes as well, that’s why it’s there for. So it looks a bit silly to loop the $page, but then again, why doesn’t it work?
You can’t loop through a page object, you can only loop through an array or a collection. Could you please be more specific about what you want to achieve? What is the intention of the foreach loop?
Maybe if you post your code, we have less guesswork to do and can help you better?
@texnixe
Ah ok, it just will not work with $page then
To give a bit more context to what I’m trying to achieve. It’s a snippet that can be placed on all kinds of templates, where the amount of events displayed is set. I also use this snippet on the event page itself, there it should only display the data of the event itself, hence just the $page.
To rephrase my question: What would be a better approach?
FYI: the snippet contains way more event data then just the H2, just to show a clean example
you leave the loop out of the snippet and only use it to display the code for the single event, so that on the events overview page, you call that single event snippet within the loop (but the loop is then part of the template)
<?php
// in your events overview page
foreach($events as $event):
snippet('single-event', ['page' => $event]);
endforeach ?>
You check if you have a collection or a single page in your snippet and then act on that.