Passing multiple variables to block

Hi! I have a block in a layout where I need to access the subpage it comes from. I tried to follow the docs but I’m still getting the undefined variable error.

'data-id' => $subpage->slug()

This is how I’m trying to pass the variable to the block

<?php snippet('layouts', ['field' => $subpage->layout(), 'subpage' => $subpage ])  ?>

You are passing the variable to your layouts snippet, but according to your description, you want to use this variable in a block snippet, not in the layouts snippets? So you would have to pass the variable on to the block. Without more code context, hard to say where it’s going wrong.

But the $subpage variable is defined (assuming you are using this in a loop).

Hi, sorry I mean a block in a layout. It’s inside a loop that defines $subpage.

<ul class="loop">
        <?php foreach ($subpages = $work->children()->listed() as $subpage): ?>
            
        <li class="project__images" id="<?= $subpage->slug() ?>" >
              <div class="project" >
                <?php snippet('layouts', ['field' => $subpage->layout(), 'subpage' => $subpage ])  ?>
              </div>
        </li>

        <?php endforeach ?>
      </ul>

Basically, I just want to use the subpage slug on the block inside the layout. Is that possible?

And what is in your layouts snippet?

Oh, maybe a big beginner’s mistake here, I didn’t change the layouts snippet from default. What should I change it to so that the variable comes through it?

<?php
/*
  Snippets are a great way to store code snippets for reuse
  or to keep your templates clean.

  This layouts snippet renders the content of a layout
  field with our custom grid system.

  More about snippets:
  https://getkirby.com/docs/guide/templates/snippets
*/
?>
<?php foreach ($field->toLayouts() as $layout): ?>
<section class="grid margin-xl" id="<?= $layout->id() ?>" style="--gutter: 1.5rem">
  <?php foreach ($layout->columns() as $column): ?>
  <div class="column" style="--columns:<?= $column->span() ?>">
    <div class="text">
      <?= $column->blocks() ?>
    </div>
  </div>
  <?php endforeach ?>
</section>
<?php endforeach ?>

First of all, I’d only pass the $subpage variable to the snippet, because then $subpage->layout() will also be available.

Secondly, if you want to pass variables to the blocks, you cannot simply echo the blocks with $column->blocks() but would have to call the blocks snippets and pass the variable on to them like this:

<?php foreach ($column->blocks() as $block): ?> 
  <?php snippet('blocks/' . $block->type(), [
    'block' => $block,
    'whatever' => 'value'
  ]) ?>
<?php endforeach ?>
2 Likes

Thanks so much! That solved everything! :slight_smile: