diff --git a/cpanfile b/cpanfile index 1c7027e..022e3f4 100644 --- a/cpanfile +++ b/cpanfile @@ -3,3 +3,4 @@ requires 'Mojo::File'; requires 'Test::Mojo'; requires 'Mojolicious::Lite'; requires 'Mojo::Pg'; +requires 'Mojolicious::Plugin::TagHelpers::Pagination'; diff --git a/guestbook-ng.pl b/guestbook-ng.pl index ca1a01c..611ecc2 100755 --- a/guestbook-ng.pl +++ b/guestbook-ng.pl @@ -11,6 +11,7 @@ use Data::Dumper; # Uncomment for debugging # Plugins plugin 'Config'; +plugin 'TagHelpers::Pagination'; # Helpers helper pg => sub { @@ -38,9 +39,21 @@ app->pg->migrations->from_dir('migrations')->migrate(1); # Routes get '/' => sub ($c) { - my $posts = $c->message->get_posts(); + my $max_posts = 5; + my $posts = $c->message->get_posts(); + my $last_page = sprintf('%d', scalar(@$posts) / $max_posts) + 1; + my $this_page = $c->param('page') || $last_page; + my $last_post = $this_page * $max_posts - 1; + my $first_post = $last_post - $max_posts + 1; + my @view_posts = grep defined, @$posts[$first_post..$last_post]; - $c->render(posts => $posts); + $c->stash( + view_posts => \@view_posts, + this_page => $this_page, + last_page => $last_page + ); + + $c->render(); } => 'index'; any '/sign' => sub ($c) { diff --git a/templates/index.html.ep b/templates/index.html.ep index 73ff448..3118ff6 100644 --- a/templates/index.html.ep +++ b/templates/index.html.ep @@ -1,7 +1,7 @@ % layout 'default'; % title 'Home';

Messages from the World Wide Web

-<% for my $row (reverse @$posts) { %> +<% for my $row (reverse @$view_posts) { %> @@ -18,3 +18,4 @@
Date:

<% } %> +<%= pagination($this_page, $last_page, '?page={page}') %>