Generic way of using content_tag for multiple elements of the same kind

ruby, ruby-on-rails

Solution

Why not something like this?

def special_label_for(field_name, label_text, span_array)
  content_tag "label", :for => field_name do
    concat label_text
    span_array.each_with_index do |span_content, index|
      concat content_tag("span", span_content, :class => "span" + index.to_s)
    end
  end
end

special_label_for :user_name, "User Name", ["This is the first Span", "And this is the second Span", "Can also have a third span", "Or as many spans as you like"]

Haven't tested this code, may need to add/remove the `concat` or an `html_safe` to get it rendering properly in your view.

Problem

I want to generate html like, ``` <label for='field'> Label Text <span class='span1'> Some Text 1 </span> <span class='span2'> Some Text 2 </span> ... </label> ``` I want a call a helper such as, `label_for 'field', :label => 'Label Text', :type1 => 'Some Text 1', :type2 => 'Some Text 2'` For which I tried to do something like, ``` content_tag(:label, opts[:label], :for => field_name) do ['span1', 'span2'].map { |i| content_tag(:span, opts[i], :class => i) if opts[i] }.compact.joins('+').html_safe } end ``` But this does not work (of course). ['span1', 'span2'] array is fixed and the user has the option of choosing to display as many spans as needed. How can I solve this problem?

Original source