Rails-вложенный content_tag - PullRequest
       5

Rails-вложенный content_tag

76 голосов
/ 17 ноября 2010

Я пытаюсь вложить теги содержимого в пользовательский помощник, чтобы создать что-то вроде этого:

<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 ]

147 голосов
/ 17 ноября 2010

Вам нужно + для быстрого исправления: 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 будет отображаться только последняя возвращенная строка.

50 голосов
/ 10 апреля 2013

Вы также можете использовать метод 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

Источник: Вложение тега content_tag в Rails 3

1 голос
/ 17 сентября 2018

построение вложенных тегов контента с итерацией немного отличается и заставляет меня каждый раз ... вот один метод:

      content_tag :div do
        friends.pluck(:firstname).map do |first| 
          concat( content_tag(:div, first, class: 'first') )
        end
      end
1 голос
/ 25 мая 2018

Я использую переменную и 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
...