循环&在 helper 的 content_tag 中输出 content_tags
我正在尝试一种帮助程序方法,它将输出一个项目列表,如下所示:
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,如果我这样做作为测试:
def foo_list items
content_tag :ul do
content_tag(:li, 'foo')
end
end
我得到UL &正如李所料。
我尝试过稍微交换一下:
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
应该在块模式下工作以某种方式收集。
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', '#' ) ... ] )
I have written the helper like so after reading Using helpers in rails 3 to output html:
def foo_list items
content_tag :ul do
items.collect {|item| content_tag(:li, item)}
end
end
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
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
试试这个:
Try this:
我无法更好地完成这项工作。
如果您已经使用 HAML,您可以像这样编写您的助手:
视图中的用法:
输出将被正确地预期。
I couldn't get that work any better.
If you were using HAML already, you could write your helper like this:
Usage from view:
Output would be correctly intended.
您可以使用
content_tag_for
,它适用于集合:更新:在Rails 5中,
content_tag_for
(和div_for
)被移动到一个单独的gem中。您必须安装record_tag_helper
gem 才能使用它们。You could use
content_tag_for
, which works with collections:Update: In Rails 5
content_tag_for
(anddiv_for
) were moved into a separate gem. You have to install therecord_tag_helper
gem in order to use them.连同上面的答案,这对我很有用:
Along with answers above, this worked for me well:
最大的问题是 content_tag 在接收数组时没有做任何明智的事情,您需要向其发送已经处理过的内容。我发现执行此操作的一个好方法是折叠/缩小数组以将其全部连接在一起。
例如,您的第一个和第三个示例可以使用以下内容代替 items.map/collect 行:
作为参考,这里是执行此代码时遇到的 concat 的定义(来自 actionpack/lib/action_view/助手/tag_helper.rb)。
The big issue is that content_tag isn't doing anything smart when it receives arrays, you need to send it already processed content. I've found that a good way to do this is to fold/reduce your array to concat it all together.
For example, your first and third example can use the following instead of your items.map/collect line:
For reference, here is the definition of concat that you're running into when you execute this code (from actionpack/lib/action_view/helpers/tag_helper.rb).