html - simple_form 自定义 inline_checkbox 标记

标签 html ruby-on-rails ruby simple-form

我正在尝试更改 label_input 的标记。

这一行(来自simple_form_bootstrap.rb,包装inline_checkbox)

  ba.use :label_input, :wrap_with => { :class => 'checkbox inline' }

以及来 self 的模板的调用:

= f.input :my_checkbox, as: :boolean, wrapper: :inline_checkbox, label: false, inline_label: "My label"

我得到以下标记:

<div class="control-group boolean optional my_checkbox">
  <div class="controls">
    <div class="checkbox inline">
      <input name="application[my_checkbox]" type="hidden" value="0">
      <label class="checkbox">
        <input class="boolean optional" id="my_checkbox" name="application[my_checkbox]" type="checkbox" value="1">
        My label
      </label>
    </div>
  </div>
</div>

我不想让复选框输入 标签,而是希望复选框输入同一个 div 的兄弟,类为“checkbox inline”,就像这样:

<div class="control-group boolean optional my_checkbox">
  <div class="controls">
    <div class="checkbox inline">
      <input name="application[my_checkbox]" type="hidden" value="0">
      <input class="boolean optional" id="my_checkbox" name="application[my_checkbox]" type="checkbox" value="1">

      <label class="checkbox">
        My label
      </label>
    </div>
  </div>
</div>

使用自定义包装器,我可以稍微更改标记,但 :label_input 始终将输入放在标签内。我怎样才能改变这种行为?理想情况下,我有一个不使用 label_input 而是使用 :label 和 :input_field 的新包装器,但我没有成功。

最佳答案

简单的表单有几种方法来呈现带有标签的复选框/单选按钮。它们在初始化文件中定义:

File: config/initializers/simple_form.rb

# Define the way to render check boxes / radio buttons with labels.
# Defaults to :nested for bootstrap config.
#   :inline => input + label
#   :nested => label > input
# config.boolean_style = :nested
config.boolean_style = :inline

您想要的是将其更改为 :inline 而不是 :nested 以便 Simple Form 仅呈现输入而没有输入上的标签包装器。参见 SimpleForm::Inputs::BooleanInput#input .

使用上述更改修改初始化文件并重新启动 Rails 服务器以使此更改生效。使用输入如下:

= f.input :my_checkbox, as: :boolean, wrapper: :inline_checkbox, label: "My label"

以下是实现类似功能的另一种方法,无需更改上述配置。我添加了一个带有 checkbox inline 类的包装器 div 来包装复选框输入和标签:

= f.input :my_checkbox do
  = content_tag :div, class: 'checkbox inline' do
    = f.check_box :my_checkbox
    = f.label :my_checkbox

关于html - simple_form 自定义 inline_checkbox 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28226130/

相关文章:

html - 下拉菜单在 IE 9 中表现怪异

HTML/CSS 文本不会跟随 div

ruby-on-rails - 运行 sidekiq 时的未定义方法 `eager_load_namespaces'

mysql - Rails 尝试插入时找不到用户记录

ruby - Capistrano 错误 - Net::SSH::HostKeyMismatch

javascript - 无法在 JS 而不是 HTML 中初始化 ng-model

python - 导入错误 : cannot import name replace_entities error when using Scrapy

ruby-on-rails - 在 CDN 中管理 Assets

ruby-on-rails - Rails 项目中的 rake 范围?

ruby-on-rails - 添加页面时 refinerycms 不工作