new guy new guy - 9 months ago 55
Perl Question

Passing arguments to redirect_to in mojolicious and using them in the target controller

I am passing arguments to redirect_to like

$c->redirect_to('named', foo => 'bar');


$c->redirect_to('named, query => {foo=> 'bar'});

but I am not sure how to use it or retrieve the value of foo in the target controller.

Answer Source

$self->redirect_to('named', foo => 'bar'), used without a preceding slash, refers to named routes, and parameters are placed into route placeholders.

Each route you define in your application gets assigned a route name by default, or you can assign them manually. (You can also get a list of assigned routes using ./myapp routes)

In a lite app:

action # route name

get '/named' => sub { ... }; # named
get '/named/:foo' => sub { ... }; # namedfoo
get '/named/:foo' => sub { ... } => 'something-else'; # something-else

The following redirects to the get '/named/:foo' action:

$self->redirect_to('namedfoo', foo => 'bar') 

Which is effectively the same as:


You can access the placeholder value within the action using ->param:

get '/named/:foo' => sub {
  my $self = shift;

Which renders the following HTML:


You might also want to check out: