Content_tag块嵌套在content_tag块内 - 表单生成器

时间:2014-07-23 00:27:59

标签: ruby-on-rails ruby twitter-bootstrap content-tag

我正在尝试使用bootstrap样式创建一个rails FormBuilder来设置表单样式:

<div class="form-group has-error">
  <label for="exampleInputEmail1">Email address</label>
  <div class="input-group>
    <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
    <span class="input-group-addon glyphicon glyphicon-user"></span>
  </div>
  <p class="help-block>can't be blank</p>
</div>

当我只有一个div标签时,我能够让表单构建器工作(排除了传统引导程序表单的输入组。我的问题是我无法使用带有类的div获取嵌套的content_tag“输入组“正常工作。我尝试添加元素并将content_tag包装在捕获中无济于事。

class LargeFormBuilder < ActionView::Helpers::FormBuilder
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::CaptureHelper
  include ActionView::Helpers::TextHelper

  attr_accessor :output_buffer

  %w(text_field text_area email_field password_field).each do |form_method|
    define_method(form_method) do |*args|
      attribute = args[0]
      options = args[1] || {}
      options[:label] ||= attribute
      options[:class] ||= "form-control input-lg"
      label_text ||= options.delete(:label).to_s.titleize
      content_tag(:div, class: "form-group #{'has-error' if !object.errors[attribute].empty?}") do
        concat label(attribute, label_text, class: "control-label")
        concat (
            content_tag(:div, class: "input-group") do
              concat super(attribute, options)
              concat content_tag(:span, "", class: "input-group-addon glyphicon glyphicon-user")
            end
         )
        concat errors_for_field(attribute)
      end
    end
  end

  def errors_for_field(attribute, options={})
    return "" if object.errors[attribute].empty?
    content_tag(:p, object.errors[attribute].to_sentence.capitalize, class: "help-block")
  end

end

2 个答案:

答案 0 :(得分:2)

实际上你不需要使用concat就可以更简单了,只需使用+以更清晰的方式获得相同的结果,只需确保第一个字符串为{{ 1}}

html_safe

并且更具可读性

content_tag(:div, class: "form-group #{'has-error' if !object.errors[attribute].empty?}") do
  label(attribute, label_text, class: "control-label").html_safe + \
  content_tag(:div, class: "input-group") do
    concat super(attribute, options)
    concat content_tag(:span, "", class: "input-group-addon glyphicon glyphicon-user")
  end + \
  errors_for_field(attribute)
end

答案 1 :(得分:0)

我认为这是一个带有bootstrap 4样式的3层深嵌套content_tag的一个很好的例子。它是一个表单助手方法,它采取行动ex。 :new或:编辑,并使用分页按钮样式的bootstrap 4输出可用的语言环境。

enter image description here

def form_lang_switcher(action)
  content_tag(:nav, :"aria-label" => 'language switch') do
    content_tag(:ul, class: 'pagination pagination-sm justify-content-end') do
      I18n.available_locales.each do |loc|
        concat content_tag(:li, (link_to loc.upcase,
                           url_for(action: :"#{action}", locale: loc), 
                           class: "page-link"), 
        class: "page-item #{(I18n.locale == loc ? "active" : "")}").html_safe
      end
    end
  end
end