simple_form with Bootstrap check box

2019-03-17 20:34发布

问题:

I'm using simple_form with Bootstrap and I would like to have my "Remember me" check box be inline to the left of the label, as in the Twitter Bootstrap docs: http://twitter.github.com/bootstrap/base-css.html#forms

My form code looks like this:

<%= simple_form_for(resource, :as => resource_name, :url => session_path(resource_name), :html => { :class => 'well'}) do |f| %>
    <%= f.input :email %>
    <%= f.input :password %>
    <%= f.input :remember_me, :as => :boolean if devise_mapping.rememberable?  %>

    <%= f.button :submit, "Sign In" %>

<% end %>

The result is the the "Remember me" label on top of a check box.

What have I messed up?

回答1:

There's a number of options for this, see here for more of them:

The most straightforward (I think) is to use :label => false and :inline_label => true, on your checkbox, to change the where in the HTML the label is placed.

<%= f.input :remember_me, :as => :boolean, :label => false, :inline_label => true if devise_mapping.rememberable? %>

This produces something like this for me:



回答2:

@alol's answer works great for a vertical form (labels on top of the fields), but if you're doing a horizontal form and you want the check box labels to show to the right of the checkbox, but still keep with the layout of the form, you can do this:

f.input :remember_me, :as => :boolean, :label => "&nbsp;", :inline_label => true if devise_mapping.rememberable?

You can also pass a specific label to use as the inline label instead of true, if you need to:

f.input :remember_me, :as => :boolean, :label => "&nbsp;", :inline_label => "My Label" if devise_mapping.rememberable?


回答3:

I think this one is a bit simpler:

f.input :remember_me, wrapper: :vertical_boolean, as: :boolean  if devise_mapping.rememberable?

The wrapper comes bundled in config/initializers/simple_form_bootstrap.rb at least from simple_form 3.1.0rc2 when installed with:

rails g simple_form:install --bootstrap