Passing object into foreach loop

Hey there,
I guess I’m missing something obvious - normally I’d go about it like this:

<?php snippet('path/to/file', ['post' => $post, 'somevariable' => $somevariable, 'gallery' => true]) ?>

… but somehow the second variable being passed cannot be used in the snippet: Undefined variable: post

Any ideas?
Cheers!

Is $post defined in the template from where you try to pass it to the snippet?

Yeah, inside a foreach loop of child posts.

Could you post your code, please?

Sure thing:

  <?php
    foreach($posts as $post) :
    $image = $post->image();
    $images = $post->images();
  ?>

  <!-- some code -->

  <?php foreach ($images as $image) : 
  // something with the second foreach loop, I guess?
  ?>
    <?php snippet('cover/postcover', array('post' => $post, 'item' => $image, 'gallery' => true)) ?>
  <?php endforeach ?>

  <!-- some code -->

<?php endforeach ?>

Cheers!

Hm, that looks ok to me.

Why has Kirby forsaken me, then!
I’ll try defining all variables in-template, but other than that, I’m helplessly confused.

// Edit:
Maybe there’s a way to fetch the page an image was uploaded to? That way I don’t need to pass $post.

Is that project online anywhere so I can take a look?

I just ported everything over from a really old Kirby version, so lots of stuff is a work in progress, but since you asked …

You call your snippet twice in your home template, on line 18 and on line 31. If you have a look at your stacktrace, you will see that your error is thrown in line 18, where you do not pass the $post variable.

1 Like

:heart:

Marvellous. Kirby Support of the day!