3

我为 simple_form 创建了一个自定义包装器,但似乎找不到将数据属性添加到生成的包装器元素的方法。我正在尝试将其添加到名为 switch 的内部包装类中。

我希望能够将它添加到包装器中,如果可能的话不在视图层中。

config.wrappers :toggle, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|
  b.use :html5
  b.use :placeholder
  b.use :label
  b.wrapper :tag => 'div', :class => 'controls' do |ba|
    ba.wrapper :tag => 'div', :class => 'switch' do |box|
      box.use :input
    end
    ba.use :hint,  :wrap_with => { :tag => 'span', :class => 'help-block' }
    ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
  end
end

= form.input :element, :label => t('views.items.attributes.element'), :wrapper => :toggle

输出

<div class="control-group boolean optional">
  <label class="boolean optional control-label" for="item_element">Element</label>
  <div class="controls">
    <div class="switch">
      <input name="item[element]" type="hidden" value="0">
      <input class="boolean optional" id="item_element" name="item[element]" type="checkbox" value="1">
    </div>
  </div>
</div>

期望的输出

<div class="control-group boolean optional">
  <label class="boolean optional control-label" for="item_element">Element</label>
  <div class="controls">
    <div class="switch" data-label="blah" data-id="something">
      <input name="item[element]" type="hidden" value="0">
      <input class="boolean optional" id="item_element" name="item[element]" type="checkbox" value="1">
    </div>
  </div>
</div>
4

2 回答 2

1

@Learner 的答案很接近。诀窍是包含一个html哈希:

ba.wrapper tag: 'div', 
           html: { data: { id: 'something', label: 'blah' }, 
           class: 'switch' do |box|
  box.use :input
end

注意:此方法适用于<builder>.wrapper方法,但不适用于config.wrappers,<builder>.use等。

于 2019-08-21T21:02:46.260 回答
0

您可以:data => {:id=> 'something', :label => 'blah'}在包装器中的标签名称之后添加

config.wrappers :toggle, :tag => 'div', :class => 'control-group', :error_class => 'error' do |b|
  b.use :html5
  b.use :placeholder
  b.use :label
  b.wrapper :tag => 'div', :class => 'controls' do |ba|
    ba.wrapper :tag => 'div', :data => {:id=> 'something', :label => 'blah'}, :class => 'switch' do |box|
      box.use :input
    end
    ba.use :hint,  :wrap_with => { :tag => 'span', :class => 'help-block' }
    ba.use :error, :wrap_with => { :tag => 'span', :class => 'help-inline' }
  end
end

= form.input :element, :label => t('views.items.attributes.element'), :wrapper => :toggle

甚至您也可以添加名称和一些值,如下所示:

:data => {:name => 'Stephen', :city_state => %w(Chicago IL)}
于 2013-02-14T11:41:35.757 回答