htmlruby-on-railsrubyhtml-tablecontent-tag

Adding a for-statement to the content_tag() method in Ruby?


This is what I want to build in Ruby on Rails:

<tr>
<td>attribute0</td>
<input name="1" type="radio" value="1" />
<input name="1" type="radio" value="2" />
<input name="1" type="radio" value="3" />
<input name="1" type="radio" value="4" />
<input name="1" type="radio" value="5" />
<td>attribute1</td>
</tr>

the number of the radio buttons should be variable. I'm using the content_tag method to generate the HTML-tags:

@template.content_tag(:tr, @template.content_tag(:td, ... ))

Is it possible to add statement like

for i in 1..5 do
    @template.tag(:input, :type => 'radio', :value => i, :name => options[:name])
end

as a parameter for content_tag?


Solution

  • You can pass in a block or use a helper. Here's an example of a helper method

    def inputs(amount, name)
      [1..amount].inject('') do |html, num| 
        html + tag(:input, type: 'radio', value: num, name: name)
      end
    end
    

    Edit: exmaple of block

    Documentation: http://api.rubyonrails.org/classes/ActionView/Helpers/TagHelper.html#method-i-content_tag

    content_tag :ul do
      5.times.map{ content_tag :li, 'element' }.reduce(&:+)
    end
    
    # same as
    
    elements = 5.times.map{ content_tag :li, 'element' }.reduce(&:+)
    content_tag :ul, elements