Exporting a variable from a snippet?

The title, basically. I know I can pass variables to the snippet, but can I get anything out of it?

What is your use case?

The snippet finds a specific page within the $site and uses it to generate some content. I want to export a reference to that page so I can use it outside the snippet as well.

I know that the logical thing is to find the page outside the snippet and then pass it inside as a variable. However, the page-finding logic is related to the snippet logic itself and doesn’t change based on what’s outside the snippet.

You could use global variables but I’m not so sure that’s a good idea.

Or you can outsource the page finding logic to a function, then use the same function in the template (won’t work if you need to pass parameters that are only known in the snippet).

I’d probably use a controller (or if you need the snippet in multiple controllers, a shared controller) for the logic and then pass the value to the snippet.

1 Like

If the snippet is not used across different templates, I’d use a controller as suggested by Sonja. Otherwise, I’d use the new shared collection.

1 Like

i solved something similar in making the snippet either echo regular logic or make it return a json string. it could be optimized in concatting all echos but i often use html mixed with php my snippets so i never did that.


$pageid = doFindPage(); // your logic
if (isset($export) && $export === true):
   echo json_encode(compact($pageid)); // ['pageid' => $pageid]
else: ?>
  <!-- do regular echo stuff in html -->
<?php endif;


snippet('mysnippet', $configArray); // echo regular snippet or...

// ... get pageid
$configArray = array_merge($configArray, ['export' => true]);
$snippetData = json_decode(snippet('mysnippet', $configArray, true));
$pageidFromSnippet = A::get($snippetData, 'pageid', null);