I'm using Sinatra and Ruby 1.9.3.
I have a list of items and want to paginate them. I'm new to web development so I don't know how to do that in detail.
I don't know how to implement the links for each page, such as the link to page2
on page1
. Should I do it like so:
<a href='?page=2'
I don't think that's a good idea because it would overwrite my other parameters like ?searchterm=
and ?sort=?
and it wouldn't take the existing ?page=
parameters into account.
My idea was to use the same form as my searchterm
etc., and change the value via buttons and JavaScript. But, that seems to be quite complicated and all big websites, including stackoverflow.com, use links for their pagination.
How do I achieve pagination which features the following:
?page=
parameter. You can always load the necessary parameters into instance vars:
@page = params[:page] || 1
and then use it as you were doing:
<a href="?page=#{@page + 1}&search_term=#{params[:searchterm]}"...
There's also a popular gem called will_paginate
which does some of this stuff automatically for you: https://github.com/mislav/will_paginate . Works with Sinatra.
## Sinatra app:
require 'will_paginate'
require 'will_paginate/active_record' # or data_mapper/sequel
You could do this, adding a little to @ChuckE's answer:
# Controller
def index
# ...
@models = MyModel.find(:yourquery)
if params[:page]
page = params[:page].to_i
@models = @models[(page * 10)..(page + 10)] # Selecting an slice out of the @models array
end
end
# In your view
- @model.each do |item|
=# do stuff
= link_to "Next Page", "?page=#{@page + 1}"
= link_to "Next Page", "?page=#{@page - 1}" unless @page = 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.