循环与在helper的content_tag中输出content_tags [英] Loop & output content_tags within content_tag in helper
问题描述
我正在尝试一个帮助程序方法,该方法将输出一个项目列表,如下所示:
I'm trying a helper method that will output a list of items, to be called like so:
foo_list( ['item_one', link_to( 'item_two', '#' ) ... ] )
在阅读在Rails中使用帮助器后,我已经这样写了该帮助器3输出html :
def foo_list items
content_tag :ul do
items.collect {|item| content_tag(:li, item)}
end
end
但是,如果我将其作为测试的话,那我只是得到一个空的UL:
However I just get an empty UL in that case, if I do this as a test:
def foo_list items
content_tag :ul do
content_tag(:li, 'foo')
end
end
我获得了UL& LI符合预期.
I get the UL & LI as expected.
我尝试将其交换一些位置:
I've tried swapping it around a bit doing:
def foo_list items
contents = items.map {|item| content_tag(:li, item)}
content_tag( :ul, contents )
end
在那种情况下,我得到了整个列表,但是LI标记是html转义的(即使字符串是HTML安全的).进行content_tag(:ul, contents.join("\n").html_safe )
可行,但是我感到不对,我觉得content_tag
应该以某种方式在集合模式下工作.
In that case I get the whole list but the LI tags are html escaped (even though the strings are HTML safe). Doing content_tag(:ul, contents.join("\n").html_safe )
works but it feels wrong to me and I feel content_tag
should work in block mode with a collection somehow.
推荐答案
尝试一下:
def foo_list items
content_tag :ul do
items.collect {|item| concat(content_tag(:li, item))}
end
end
这篇关于循环与在helper的content_tag中输出content_tags的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!