Kashia is proud to present you this little tip:

How to implement a Pager

So, you've got a lot of data, which just won't fit on your page? You want it nicely spread over a few pages, and you just don't want to reinvent the wheel or spend hours doing it?

Here's how you do it:

First, your run.rb, to require the needed file

# ... other stuff here

require 'nitro/helper/pager'

# ... Og.setup, Og.start etc.

Your data:

model.rb

class Foo
  property :title
end

Then your controller:

controller.rb

class MyController < Nitro::Controller
  helper :pager

  def action
    @entries, @pager = paginate(Foo, :per_page => 10)
  end
end

The most important things here are:

  • helper: this loads the helpers, here it loads just the pager
  • paginate: this returns the "Foo" entries, and a pager object

Now, how to use them in a template:

action.xhtml

<!-- other html -->
<ul>
<?r @entries.each do |foo| ?>
  <li>#{foo.title}</li>
<?r end ?>
</ul>
<div class="pager">
  #{@pager.navigation}
</div>
<!-- other html -->

So, you handle the @entries, like you normally would, and then just use the @pager somewhere you like.

@pager.navigation returns a list of pages, and first/last/next/previous links. You can use CSS to format them nicely.

I hope that tip is useful for you, thank you for reading!