use Mojolicious::Lite -signatures; # turns on strict and warnings too use Mojo::SQLite; use Hash::Ordered; helper sqlite => sub { state $sql = Mojo::SQLite->new('sqlite:/path/to/mydb.db') }; # disable template cache when running under morbo/development mode app->renderer->cache->max_keys(0) if app->mode eq 'development'; # define the database columns; used everywhere in this script # and most code depends on this hash being ordered tie my %COLS, 'Hash::Ordered', nick=>'Nickname', pic=>'Picture', say=>'Says', likes=>'Likes', fav=>'Favorite vehicle', car=>'Real life car/vehicle', age=>'Age', town=>'Hometown', drink=>'Favorite drink', wpage=>'Webpage'; # dynamically generate the table definition based on the columns # (if columns are modified later this might mess things up) my $CREATE = app->sqlite->abstract->generate('create table', 'drivers', [ 'id INTEGER PRIMARY KEY AUTOINCREMENT', map {"$_ TEXT"} sort keys %COLS ] ); app->sqlite->migrations->from_string(<<"END_MIGR")->migrate; -- 1 up $CREATE; -- 1 down DROP TABLE IF EXISTS drivers; END_MIGR # a normal GET request queries the database and renders the template get '/' => sub ($c) { $c->stash( COLS => \%COLS, rows => $c->sqlite->db->select('drivers', [keys %COLS])->hashes ); $c->render('main'); } => 'drivers'; # a POST request adds a row to the database and redirects back post '/' => sub ($c) { $c->sqlite->db->insert('drivers', { map { $_=>$c->param($_) } keys %COLS } ); $c->redirect_to($c->url_for('drivers')); } => 'newdriver'; app->start; __DATA__ @@ main.html.ep Drivers

Drivers

% if (@$rows) {
% for my $col (values %$COLS) { % } % for my $row (@$rows) { % for my $col (keys %$COLS) { % } % }
<%= $col %>
% if ($col eq 'pic') { %= image $row->{$col} % } elsif ($col eq 'wpage') { %= link_to $row->{$col} => $row->{$col} % } else { %= $row->{$col} % }
% } else {
No records found!
% }

Add a New Driver

%= form_for newdriver => ( method => 'post' ) => begin % for my $col (keys %$COLS) { % }
<%= label_for $col => $COLS->{$col} %> % if ($col eq 'pic' || $col eq 'wpage') { %= url_field $col, placeholder=>'https://example.com/...', required=>'required', pattern=>'https://.*' % } else { %= text_field $col, placeholder=>$COLS->{$col}, required=>'required' % }
%= submit_button 'Add Driver' %= end