Rails嵌套的content_tag

时间:2010-11-17 14:54:05

标签: ruby-on-rails ruby-on-rails-3 helpers

我正在尝试将内容标记嵌套到自定义帮助程序中,以创建如下内容:

<div class="field">
   <label>A Label</label>
   <input class="medium new_value" size="20" type="text" name="value_name" />
</div>

请注意,输入与表单无关,它将通过javascript保存。

这是助手(它会做更多然后只显示html):

module InputHelper
    def editable_input(label,name)
         content_tag :div, :class => "field" do
          content_tag :label,label
          text_field_tag name,'', :class => 'medium new_value'
         end
    end
end

<%= editable_input 'Year Founded', 'companyStartDate' %>

但是,当我调用帮助程序时,不会显示标签,只显示输入。如果它注释掉text_field_tag,则显示标签。

谢谢!

4 个答案:

答案 0 :(得分:146)

您需要+来快速修复:D

module InputHelper
  def editable_input(label,name)
    content_tag :div, :class => "field" do
      content_tag(:label,label) + # Note the + in this line
      text_field_tag(name,'', :class => 'medium new_value')
    end
  end
end

<%= editable_input 'Year Founded', 'companyStartDate' %>

content_tag :div块内,只会显示最后返回的字符串。

答案 1 :(得分:50)

您还可以使用concat方法:

module InputHelper
  def editable_input(label,name)
    content_tag :div, :class => "field" do
      concat(content_tag(:label,label))
      concat(text_field_tag(name,'', :class => 'medium new_value'))
    end
  end
end

来源:Nesting content_tag in Rails 3

答案 2 :(得分:1)

我使用变量和concat来帮助更深入的嵌套。

def billing_address customer
  state_line = content_tag :div do
    concat(
      content_tag(:span, customer.BillAddress_City) + ' ' +
      content_tag(:span, customer.BillAddress_State) + ' ' +
      content_tag(:span, customer.BillAddress_PostalCode)
    )
  end
  content_tag :div do
    concat(
      content_tag(:div, customer.BillAddress_Addr1) +
      content_tag(:div, customer.BillAddress_Addr2) +
      content_tag(:div, customer.BillAddress_Addr3) +
      content_tag(:div, customer.BillAddress_Addr4) +
      content_tag(:div, state_line) +
      content_tag(:div, customer.BillAddress_Country) +
      content_tag(:div, customer.BillAddress_Note)
    )
  end
end

答案 3 :(得分:1)

通过迭代构建嵌套的内容标签有点不同,每次都会让我...这是一种方法:

      content_tag :div do
        friends.pluck(:firstname).map do |first| 
          concat( content_tag(:div, first, class: 'first') )
        end
      end