Using snippets for returning page fragments, and generating routes for them

On a project I am working on, I need to be able to define the HTML returned, instead of returning the full page. So I thought of using snippets to return exactly the content I need. Now, I need routes to these page fragments. Is it possible to pre-generate these routes?

I am using this function to generate them:

function generate_spots_routes() {
  $spots = kirby()->page('spots')->children();
  $routes = [];

  foreach($spots->toArray() as $spot) {
    $routes[] = [
      'pattern' => $spot['id'],
      'action' => function() {
        return snippet($spot['uid'], ['data' => kirby()->page($spot['uid'])], true);
      }
    ];
  }

  return $routes;
};

and then in config.php:

return [
  'routes' => [...generate_spots_routes()]
];

and the page breaks. What am I doing wrong?

The error comes from calling kirby() in the config. You cannot do that.

What I don’t understand is why you don’t do it like this:

'routes' => [
  [
      'pattern' => 'spots/(:any)',
      'action' => function($uid) {
          return snippet($uid, ['data' => page('spots/' . $uid)]);
      }
  ]
],

It was that simple :man_facepalming:t2:! Thanks!