perlcgidancer2

How to continue to empty template when URL data is missing in Perl Dancer2


I have this route in my Dancer app: get '/newplayer/:name/:team/:season' => sub { that is called like this: https://website.com/newplayer/Joe Smith/Tigers/Fall 2024 and collects data from the url and put's into a form in the template newplayer.tt so that when the user arrives at the page this information is already mostly filled in.

It works great but I am looking for a way for the route to still be found if there are no values supplied at the url, so that if the user goes to https://website.com/newplayer they still arrive at the page, albeit with an empty form, instead of getting a 404 error. Does anyone know how I can do this?


Solution

  • You can use a forward. Using the megasplat ** instead of /:name?/:team?/:season? would make it work for partial information, too (e.g. /newplayer/Joe Smith).

    get '/newplayer' => sub {
        forward '/newplayer///'
    };
    
    get '/newplayer/**' => sub {
        my @params = splat();
        my ($name, $team, $season) = @{ $params[0] };
        template('newplayer', {name => $name, team => $team, season => $season})
    };