NAME
Mojo::Manual::Mojolicious - Mojolicious
ROUTES
Routes allow you to map requests to controllers and actions.
Simple route
Let's look at this example.
# /articles
$r->route('/articles')->to(controller => 'article', action => 'list');
When a user requests /articles
, the module Article.pm
is loaded and the method list
will be called. controller
and action
values are important, because they decide what is going to be called if a path matches the given pattern.
Additional parameters
Besides controller
and action
you can define as many parameters as you like.
# /articles (sort_by = 'date')
$r->route('/articles')
->to(controller => 'article, action => 'list', sort_by => 'date');
Placeholders
Pattern can be more specific and automatically provide parameters through placeholders.
# /*
$r->route('/:controller')->to(action => 'list');
The colon means that controller
will be automatically captured and passed along.
Default values
You can specify default values for all parameters.
# /* (id = 1)
# /*/*
$r->route('/:controller/:id')->to(action => 'view', id => 1);
The value for id
will be 1
if it's not specified.
Constraints
Parameters can also have constraints.
# /articles/5
$r->route('/articles/:id', id => qr/\d+/)
->to(controller => 'article', action => 'view');
This will only match if id
is a number. There is no need to specify ^
and $
, because they are automatically added.
Optional parameters
Values are required if no default value was given. You can also just set default values to undef
to make them entirely optional.
# /archive
# /archive/2008
$r->route('/archive/:year')
->to(controller => 'archive', action => 'list', year => undef);
Nested routes
Don't repeat yourself. For a given root pattern you can have multiple nested pattern. This can be used to factor out repetitive code.
# /books/5/edit
# /books/5/delete
my $b = $r->route('/books/:id')->to(controller => 'book');
$b->route('/edit')->to(action => 'edit');
$b->route('/delete')->to(action => 'delete');
Bridges
Sometimes it is necessary to call multiple method after another (e.g. authorization, data processing). That's what bridge
is for.
# /blog
$r->bridge->to(controller => 'foo', action =>'auth')
->route('/blog')->to(action => 'list');
Foo::auth
will be called before Foo::list
. If Foo:auth
does not return a true value, the chain will be broken and return without Foo::list
being called.
Waypoints
Waypoint is something in between bridges and nested routes. It can match even if it's not an endpoint, but will behave just like route
if children are matching too.
# /books
my $b = $r->waypoint('/books')->to(controller => 'books', action => 'list');
# /books/1
$b->route('/:id', id => qr/\d+/)->to(action => 'view');
Quoted symbols
It is not only possible to catch parameters from slash to slash, you can also quote them with parentheses for more advanced matching.
# /view-5
# /delete-1
$r->route('/:(action)-:(id)')->to(controller => 'album');