Routing/virtual pages

Hi there!

I read the docs about the virtual pages however I can’t figure out how to achieve the following.

The content folder has the following structure (folder names):

– home
– ourproducts
   – cars
      – car1
      – car2
   – balloons
      – balloon1
      – balloon2

So the URL to a product subpage is
www.example.com/ourproducts/cars/car2

However I’d like the URL to say products instead of ourproducts

(For some specific unrelated reason I can’t simply change the folder’s name to products.)

So I thought about Kirby’s router – is it possible to change the URL from
www.example.com/ourproducts/cars/car2
to
www.example.com/products/cars/car2
using the router config?

Unfortunately categories like cars or balloons are dynamic pages, so more categories could be added by the client.

I read the virtual pages docs but am none the wiser.

Thanks for any input!

Yes, you can do that. Your route can contain placeholders. We use two routes, where the second is just a fallback just in case.

'routes' => [
   [
      'pattern' => 'products',
      'action'  => function () {
        // return ourproducts page
      }
    ],
    [
      'pattern' => 'products/(:all)',
      'action'  => function ($uri) {
        // go find the page in the ourproducts folder
      }
    ],
    [
     // send anyone who want to access ourproducts/* to `products`
      'pattern' => 'ourproducts',
      'action'  => function () {
        go('products');
      }
    ],
    [
     // send anyone who want to access ourproducts/* to `products`
      'pattern' => 'ourproducts/(:all)',
      'action'  => function ($uri) {
        go('products/' . $uri);
      }
    ]
  ]

Additionally, you might want to overwrite the url() method for all three page models

2 Likes

Oh, thank you very much for the explanation and the snippet @texnixe !

If you’re really lazy like me, you can also do that with a plugin:wink:

1 Like