Snippets

Brian Medley Filter example

Created by Brian Medley
use Mojolicious::Lite;

sub filter {
    my ($route, $c, $captures, $options) = @_;

    return undef unless $options;
 
    $DB::single = 1;

    foreach my $name (keys %{ $options }) {
        my $value = $options->{$name}->($c, $name, $c->req->param($name));

        $c->req->param($name, $value);
    }
 
    return 1;
}

app->routes->add_condition(filter => \&filter);

get "/" => sub {
    my $c = shift;

    $c->render(template => "data");
};

sub upper {
    uc(pop);
}

post "/upper" => (filter => {joy => \&upper}) => sub {
    my $c = shift;

    $c->stash("output", $c->param("joy"));

    $c->render(template => "data");
};

post "/same" => sub {
    my $c = shift;

    $c->stash("output", $c->param("joy"));

    $c->render(template => "data");
};

app->start;

__DATA__

@@ data.html.ep
<!DOCTYPE html>
<html>
  <body>
    "<%= stash('output') %>"
    <form action="/upper" method="post">
        <input type="text" name="joy">
        <input type="submit" name="submit" value="Submit">
    </form>
    <hr>
    <form action="/same" method="post">
        <input type="text" name="joy">
        <input type="submit" name="submit" value="Submit">
    </form>
  </body>
</html>

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.