Sometimes I need to get the matched pattern from a route.
It can be done like this:
kirby()->routes([
[
'pattern' => ['jens', 'erik'],
'action' => function() {
echo $this->kirby->request()->path()->first(); // jens
}
],
]);
Is this the official way to do it? I think it’s quite long. I would prefer to have it like:
echo $this->pattern();
But it looks like with $this
I get the full kirby object so $this->pattern
would not make sense there.
texnixe
December 11, 2017, 5:46pm
2
Don’t know what your are doing with the $this
variable, but this should work:
kirby()->routes([
[
'pattern' => ['jens', 'erik'],
'action' => function() {
echo kirby()->route()->pattern();
}
],
]);
Ahh, that’s better. I also found out that it’s possible to use $this->kirby->route()->pattern()
but it’s longer.
My full route now looks like this:
<?php
global $kirby;
foreach(page('static')->children() as $item) {
$pattern[] = $item->slug();
}
$kirby->routes([
[
'pattern' => $pattern,
'action' => function() {
$uid = 'static' . '/' . kirby()->route()->pattern();
return site()->visit($uid);
}
],
]);
What about this?
$slugs = page('static')->children()->pluck('slug');
$kirby->routes([
[
'pattern' => '(' . implode('|', $slugs) . ')',
'action' => function($slug) {
$uid = 'static' . '/' . $slug;
return site()->visit($uid);
}
],
]);
That’s probably the more official way to do this.
But apart from that: I have noted the idea to provide the route object as $this
for Kirby 3. We will still need to check if that even makes sense though (maybe it breaks another use-case).
2 Likes
texnixe
December 21, 2017, 8:01pm
5
Yeah, that’s a nice way of solving this, didn’t think of converting the array to a placeholder…