新手问题 [已解决] simple_form 里如何设置 input 的 wrapper 的 class?

chairy11 · 2014年01月04日 · 最后由 chairy11 回复于 2014年01月08日 · 4443 次阅读

bootstrap 表格总是默认 width:100%,我希望把它变成 col-xs-12 col-sm-6 col-md-4,左 label,中 input,右 hint。

目前用 simple_form,在设置里,我:

config.wrappers :bootstrap, tag: 'div', class: 'form-group', error_class: 'error' do |b|  
    b.use :input, wrap_with: { tag: :div, class: 'input_wrapper'} 
  end

所以:

<%= f.input :nick, :required => true%>

生成的 html 为:

<div class="form-group ">
  <label class="control-label col-sm-2 " > 昵称</label>
  <div class="input_wrapper">
    <input class="form-control"  >    
  </div>
</div>

我的问题是: 如何向包围着 input 的 div 注入 class:"col-xs-12 col-sm-6 col-md-4"? 目标是生成:

<div class="form-group ">
  <label class="control-label col-sm-2 " > 昵称</label>
  <div class="input_wrapper col-xs-12 col-sm-6 col-md-4">
    <input class="form-control"  >    
  </div>
</div>

注: form-control 控制着 width:100%, 所以我曾用 input_html: {class: 'col-sm-6 col-md-4'}得到 input 本身 class 的注入, 即结果为:

div class="form-group ">
   <label class="control-label col-sm-2 " > 昵称</label>
    <input class="form-control col-xs-12 col-sm-6 col-md-4"  >    
</div>

此问题有解吗?

高手们都是怎么解决 bootstrap 的表格宽度问题的?


补充: 我试过设置 config 里声明

b.wrapper :my_wrapper do |component|
    component.use :input,  wrap_with: { tag: :div }
end

这样倒是可以使用 my_wrapper_html: {class: "col-xs-12 col-sm-6 col-md-4"}注入 class 但又会生成两个 input,如果光用:my_wrapper 貌似又不行……

1 楼 已删除

#1 楼 @liwei78 ?不对,你这个是 input 级的 class,我要再上一级的。

#2 楼 @chairy11 为何不看文档和 wiki

https://github.com/plataformatec/simple_form/wiki/Custom-Wrappers

= f.input :remember_me, :wrapper => :inline_checkbox

别用他了,情愿手动写生成的 html, 直观。 以前一直在纠结这些 gem 的生成,太浪费时间了。尤其现在都是大段复制 bootstrap 样例再修改的情况。

#3 楼 @Victor 谢谢。 之前有看文档,但没有看懂。你的例子之前也没看懂。现在看懂了。

应该是先单独来个

config.wrappers :input_wrap do |b|
  b.use :html5
  b.use :placeholder
  b.use :label
  b.use :input, wrap_with: {tag: 'div', class: 'col-xs-10 col-sm-6 col-md-5 col-lg-4'}
  b.use :error, wrap_with: { tag: 'span', class: 'help-inline' }
  b.use :hint,  wrap_with: { tag: 'span', class: 'help-block' }
end

再在使用时

<%= f.input :email,  wrapper: :input_wrap %>
需要 登录 后方可回复, 如果你还没有账号请 注册新账号