Good forms helpers for Sinatra?

2020-06-22 07:06发布

问题:

I am starting to do forms and am looking for form helpers in Sinatra.

  • Sinatra doesn't seem to have built-in forms helpers.
  • The helpers in Padrino look like what I'm after but I don't feel up to porting my app to another framework. Plus it's starting to look like a Rails application.
  • I haven't found any Sinatra forms helpers out there that are the 'de facto' choice.

Ideally, I'm after just a set of decent forms helpers that I can include as a gem and just start using, in place of hand-rolling all the base level erb/haml/ruby forms building.

What are your recommendations?

回答1:

I find sinatra-formhelpers useful and used it in some projects. Have a look at their Github page, the code is pretty straightforward and might just be what you are looking for. Even if not, you could add your own specialized helpers easily. You can simply install it with

gem install sinatra-formhelpers

and use it by requiring the Gem:

require 'sinatra/form_helpers'

or, if you subclass Sinatra::Base, by additionally including the helpers:

class MyApp < Sinatra::Base
  helpers Sinatra::FormHelpers
  # ...
end

After all, part of Sinatra's philosophy is to be as light as possible. So if you want all the fancy things built in, Sinatra might just not be the right tool.



回答2:

I recommend using sinatra-formhelpers-ng because it fixes a bug in sinatra-formhelpers.

I too found sinatra-formhelpers useful but it didn't appear to be maintained and I ran into a bug: the state of SELECT tags is not persisted across form submissions. So in other words, if I make a form with a bunch of fields and two dropdown lists (SELECT tags), all the fields are persisted if I say want to rerender the form in the POST due to failing validation except the SELECT tags. I fixed this and pushed it to the original sinatra-formhelpers repo. The push was accepted but the gem was not updated. I waited a couple weeks and then forked it to sinatra-formhelpers-ng.