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

2

7

I am passing arguments to redirect_to like

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

or

$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.

Methodize answered 8/3, 2012 at 17:44 Comment(0)
J
13

$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:

$self->redirect_to('/named/bar');

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

get '/named/:foo' => sub {
  my $self = shift;
  $self->render_text($self->param('foo'));
};

Which renders the following HTML:

bar


You might also want to check out: http://mojocasts.com/e2#Generic%20Placeholders

Jay answered 8/3, 2012 at 19:1 Comment(1)
If I want to pass more data to redirected page I should use $self->session->{ data => [ 'z' ] } should not? and access that data in target controller $self->session->{ data }[0] #zMastic
M
5

Very verbose explanation how to pass and get param

$self is a mojolicious controller. In each case, we call $obj->param for a list of names, $obj->param("arg") for the value (or list of values):

$self->param             -- params from route, post and get
$self->req->param        -- params from post and get
$self->req->query_params -- params from get
$self->req->body_params  -- params from post
Mastic answered 1/12, 2016 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.