Alister West

home is where your code is ...

Mojolicious::Lite examples

M::L routing examples

#!/usr/bin/env perl
use Mojolicious::Lite;

app->secret('no-secret-warnings off');
app->mode('production'); # stop debug pages

# Mojolicious::Lite puts several commands in the callers namespace.
# (app, get, post, ...)

# alias $self so acts just like Mojolicious (non-lite)
my $self = app();

my $r = $self->routes;
$r->get('/' => sub {
    my $self = shift;
    # get hash of params.
    # use $self->req->param instead of $self->param to stop
    # placeholder key/vals from polluting param space.
    my %params = map { my @v = $self->req->param($_);
        $_ => @v > 1 ? \@v : $v[0] } $self->req->param;

    $self->render('index');
});

# Package stuff for scrunching a condensed app into one file.
package Foo;
use base 'Mojolicious::Controller';
sub baz { shift->render( text => '*{Foo::Baz} => say bar!' ); }

package main;
# Default name() is appended to controler-action.
$r->get('/foo/bar')->to('foo#bar'); # name => 'foobar' - routes to Foo::bar
$r->get('/foo/baz')->to('foo#baz'); # name => 'foobaz' - no sub - renders template
$r->get('/foo/sam')->to(); # renders 'foosam.html.ep', not 'foo/sam.html.ep'

app->start;
__DATA__

@@ index.html.ep
Welcome to my Mojolicious!

@@ foo/bar.html.ep
Welcome to Foo Baz!

@@ foo/sam.html.ep
Sam i AM Controller / Action

@@ foosam.html.ep
Sam i AM




#!/usr/bin/env perl
BEGIN {$ENV{MOJO_MODE} ||='production'}
use Mojolicious::Lite;

app->secret('stop warnings about no-secret');

get '/:action/:value' => sub {
    ...
}

get '/*catchall' => sub { 
    my $msg = 'These are not the droids yous are looking for.';
    shift->render( text => $msg );
} 

Mojolicious routing magic - html, js, css

#!/usr/bin/env perl
use lib "/home/alister/perl5/lib/perl5";
use Mojolicious::Lite;
get "/" => 'foo';
# get $route_re => \@restrictions => \%defaults => \&coderef => $name;
# We are expliciting naming routes here so we can refer to them with url_for
get "/foo\.js"  => { template => 'foo', format => 'js' } => 'foo-js';
get "/foo\.css" => { template => 'foo', format => 'css'} => 'foo-css';

# You can also get the same result with:
# get "/foo" => "foo";
# <% url_for "foo", format => 'css' %>

app->start;
__DATA__

@@ foo.html.ep
<html>
<head><title>Foo</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script src="<%= url_for 'foo-js' %>"></script>
    <link rel="stylesheet" type="text/css" href="<%= url_for 'foo-css' %>">
</head>
<body><h1>This is Foo</h1><div id=content><p>Lorem Ipsum</p></div></body>
</html>

@@ foo.js.ep
/* this is foo.js, double the amount of Lorem's */
$(function(){ $('#content').append( $('<p>and more Ipsums..</p>') ) });

@@ foo.css.ep
h1 { color: #eaa; font-size: 36px; }

Bridge example for authentication

#!/usr/bin/env perl
use Mojolicious::Lite;
my $self = app();

my $public = $self->routes;
$public->route("/"     )->to( cb => sub { shift->render(text => "to slash\n") });

$public->route("/main" )->to( cb => sub {
    my $self = shift;
    $self->render( text => "to Main::index (". $self->session('user') .")\n");
});

$public->get("/login" )->to( cb => sub {
    my $self = shift;
    $self->session( user => 'Bender');
    $self->render(text => "Logged in as Bender\n")
});

$public->get("/logout")->to( cb => sub {
    my $self = shift;
    $self->session( user => '' );
    $self->render(text => "You are logged out\n")
});

my $auth = $public->bridge->to(cb => sub { my $self = shift;
    return 1 if $self->session('user');
    # do a redirect to /login here.
    $self->render( text => 'You are not logged in');
    return;
 });

$auth->get("/foo")->to( cb => sub { shift->render(text => "this is foo\n"); });

$self->start;

Contact-Us

Simple contact-us page. Adds custom header to email so you email-server knows can filter web-enquires from email-enquires.

#!/usr/bin/env perl
use local::lib "~/perl5";
use Email::Sender::Simple qw(try_to_sendmail);
use Email::Simple;
use Mojolicious::Lite;

# SETUP
app->secret('random string to turn off warnings about no secret');
app->mode('production'); # stop debug output
my $admin_email = 'enquiry@example.com';

any '/' => sub {
    my $self = shift;
    my $params = $self->req->params->to_hash;
    if ($params->{submit}) {

        # send an email
        my $email = Email::Simple->create(
            header => [
                To       => $admin_email,
                From     => $params->{from},
                Subject  => $params->{subject},
                'X-Site' => 'example.com:webform-enquiry',
            ],
            body => "$params->{content}\n",
        );

        $self->stash( 'message', try_to_sendmail($email) ? "Email Sent" : "Errors - not sent" );
    }
    $self->render('index');
};

app->start;
__DATA__

@@ index.html.ep
% title 'Contact';
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body>
    <form action="<%= url_for("/") %>" method="POST">
    <fieldset>
        <div>From: <input type=text name=from value="<%= param 'from' %>"></div>
        <div>Subject: <input type=text name=subject value="<%= param 'subject' %>"></div>
        <div>Message: <textarea name=content><%= param 'content' %></textarea></div>
        <div><input type=submit name=submit value=submit></div>
    </fieldset>
    </form>
    <hr>
    <div style="color:green"><%= stash 'message' %></div>
</body>
</html>
By Alister West