Iโve been playing around with routes today and want to share some things.
Goal
My goal here was to make page urls like tags/amounts/1000
to 1000
.
Merge a collection of pages
First I needed to get all the pages for the route, merge 2 collections into 1.
$tag = new Pages();
$tag->add(page('tags/amounts')->children());
$tag->add(page('tags/topics')->children());
Create patterns
Then I wanted each slug to be a pattern.
- For the route to allow
$uid
to be used I needed to wrap the slugs into()
. - To know
$id
, I use that as key in the array. The route does not care about the key.
foreach($tag as $item) {
$tags[$item->id()] = '(' . $item->slug() . ')';
}
The route
- As pattern I use
$tags
which is the array from above. - I put
use ($tags)
to be able to use the$tags
array inside the action. - I get the key which is the page id which I use for
site()->visit($key)
.
$kirby = kirby();
$kirby->set('route', [
'pattern' => $tags,
'action' => function($uid) use ($tags) {
$key = array_search("($uid)", $tags);
return site()->visit($key);
}
]);
For me itโs a different way to work with routes with a few new tricks. I hope someone finds it useful.