Passing variables to modules

Hi all,

I am trying to pass a variable when using Kirby Modules but having no luck.

site.php controller is:

<?php

return function ($page, $pages, $site, $kirby) {
    $example = 'duck';

    return compact(
        'example'
    );
};

and in home.php template I have:

<?= $page->modules([
  'example' => $example,
]) ?>

This however isn’t working for me. :frowning:

No, the modules method doesn’t accept parameters, it returns a modulescollection.

What are you trying to achieve?

Thanks for the reply @texnixe. My end goal is to be able to iterate over and print the modules created using ‘Kirby Modules’ and pass them variables that are defined in page/site controllers.

As the modules exist as snippets, I thought I may be able to pass the variables in a similar way.

You have access to the $page object in a module. Accessing the page’s controller is really easy:

$controller = kirby()->controller('default', [$page]);

Thanks @texnixe & @thguenther for pointing me in the right direction.

I ended up iterating over the modules then passing the variables.

<?php
$modules = $page->modules();
// Iterate over the modules
foreach ($modules as $module): ?>
  <?php 
  $template = $module->intendedTemplate();
  // Remove the first occurrence of 'module.' text that is placed in front of the template name
  $template = preg_replace('/\bmodule.\b/', '', $template, 1);
  // Call the correct module and variables to the snippet
  snippet('modules/' . $template, compact('module', 'example', 'variables')) ?>
<?php endforeach ?>

FYI: I just pre-released version 2.5.2 that allows you to pass variables to the renderModules() method like this:

<?= $page->renderModules([
  'test' => 'your stuff'
]) ?>