Skip to content

Latest commit

 

History

History
99 lines (76 loc) · 2.7 KB

routing.md

File metadata and controls

99 lines (76 loc) · 2.7 KB

Routing

kirby()->routes()

For plugins it's quite common to use the syntax below.

kirby()->routes(array(
  array(
    'pattern' => 'my/awesome/(:any)',
    'action'  => function($uid) {
      echo $uid;
    }
  )
));

Return a response or site visit

Instead of use echo or return false; to output or return something from a route, you can create a response object.

Response exemples

return new Response('Hello World!', 'html', 200);
return new Response('You have an error!', 'html', 404);
return new Response(json_encode(['Hello' => 'World']), 'json', 200);
return new Response(snippet('error-message', [], true), 'html', 404);

Visit examples

The syntax site()->visit('error') will not work if you change c::set('error'). The example below is better in that case.

return site()->visit(site()->errorPage());

Full example

kirby()->routes(array(
  array(
    'pattern' => 'some/page',
    'action'  => function() {
      return new Response('You have an error!', 'html', 404);
    }
  )
));

Regular expressions

Pattern examples

'pattern' => '(.+)',           // Match all
'pattern' => '(?!assets)(.*)', // Match all except the assets folder

Full example

kirby()->routes(array(
  array(
    'pattern' => '(.+)',
    'action' => function($uri) {
      echo $uri;
    }
  )
));

Built in patterns

'(:num)'     => '(-?[0-9]+)',
'(:alpha)'   => '([a-zA-Z]+)',
'(:any)'     => '([a-zA-Z0-9\.\-_%=]+)',
'(:all)'     => '(.*)',
'/(:num?)'   => '(?:/([0-9]+)',
'/(:alpha?)' => '(?:/([a-zA-Z]+)',
'/(:any?)'   => '(?:/([a-zA-Z0-9\.\-_%=]+)',
'/(:all?)'   => '(?:/(.*)',