Rails 嵌套的 content_tag

我试图将内容标记嵌套到一个自定义助手中,以创建类似下面这样的东西:

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

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

下面是 helper (它不仅仅是显示 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' %>

但是,当我调用 helper 时,标签不会显示,只显示输入。如果它注释掉 text _ field _ tag,则显示标签。

谢谢!

54298 次浏览

You need a + to quick fix :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' %>

Inside the block of content_tag :div, only the last returned string would be displayed.

You can also use the concat method:

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

Source: Nesting content_tag in Rails 3

I use a variable and concat to help with deeper nesting.

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

building nested content tags with iteration is a little different and gets me every time... here is one method:

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