1

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?

4

1 回答 1

2

你可以传入一个块或使用一个助手。这是辅助方法的示例

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

编辑:块的例子

文档: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
于 2012-12-06T14:23:05.140 回答