Controllers and snippets


In my template I use:

<?php $filteredPages = $page->parent()->children()->listed()->not($page)->filterBy('cat', $category, ',')->limit(3); ?>

All work correctly, but I’m trying to move all my html in a snippet, and when I do it, have an error: Undefined variable: category

I also tried to use it in a controller, but did not work.

Thank you for advices.

If you move stuff from a template to a snippet, you have to pass your variables along to the snippet, if they are not defined inside the snippet.

$category = 'whatever'; // the variable is probably define in your controller, just putting it here for clarity
snippet('your_snippet', ['category' => $category]) ?>

Yes, $category is defined in the parent controller, and passing the variable along the snippets works just fine.

Thank you.