How to apply route also to .json.php?

In a website I’m working on I collect all the content (articles) in the page ‘home’.
In order to have cleaner URLs I’m Removing the parent page slug from the URL.

Since some of this content is passed to Three.js, I have a home.json.php & article.json.php, which are not accessible anymore after I applied the route.

I really don’t understand why and how to make the json files accessible again…
Anyone could explain me what is the problem and how to solve it?

Many thanks!

Could you please post your route?

Is very similar to the one from the guide:

'routes' => [
      [
        'pattern' => '(:any)',
        'action'  => function($uid) {
            $page = page($uid);
            if(!$page) $page = page('home/' . $uid);
            if(!$page) $page = site()->errorPage();
            return site()->visit($page);
        }
      ],
      [
        'pattern' => 'home/(:any)',
        'action'  => function($uid) {
            go($uid);
        }
      ],
    ],

Thanks for having a look!

This here returns the error page for all routes that are not a page. So try

 [
        'pattern' => '(:any)',
        'action'  => function($uid) {
            if ($page = (page($uid) ?? page('home/' . $uid))) {
                return site()->visit($page);
            }
            $this->next();
           
        }
 ],

Not working… same behavior of my code: when I try to load the .json instead of rendering the data, it just reloads the page

Which Kirby version are you using? Do you have a multi-language site?

This should work:

  [
          'pattern' => '(:any)',
          'action'  => function ($uid) {
              if (Str::contains($uid, 'json')) {
                  $this->next();
              }
              if ($page = (page($uid) ?? page('home/' . $uid) ?? null)) {
                  return $page;
              }
              return $this->next();
          }
        ],

The alternative would be to use a regex pattern instead of (:any) that excludes patterns with a dot

I’m using Kirby 3.7.3, the website is only in one language.

Using your last piece of code I’m able to load website.test/home.json, but when trying to load the json of a page, for example website.test/article.json, it returns the error page. While the page itself is loading correctly.

Do you think I should solve this with a regex pattern, or it’s something else?

I’d use a regex pattern, then you don’t need the ugly if statement