在 Rails 中,如何制作循环助手?
假设我想创建一个 HTML 列表助手,它允许我循环遍历集合,并且仅输出
或
标签(如果存在)是任何列表项(我实际上想到的是有点令人讨厌,但这可以作为一个例子)。像这样的东西:(
<% html_list(:ul, MyModel.all) do |my_model| %>
<span><%= my_model.id %></span>
<% end %>
正如你所知,我迷路了。)
我无法理解我的 html_list
方法中会发生什么。你介意给我指出正确的方向吗?
Let's say I want to create an HTML list helper that would allow me to loop through a collection, and only output the <ul>
or <ol>
tags if there are any list items (what I actually have in mind is a bit nastier, but this'll work for an example).
Something like:
<% html_list(:ul, MyModel.all) do |my_model| %>
<span><%= my_model.id %></span>
<% end %>
(As you can tell, I'm lost.)
I cannot wrap my head around what would go in my html_list
method. Would you mind pointing me in the right direction?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可能想要这样的东西:
或者也许这样:
有多种方法来构建最终的字符串,它的核心是你正在构建一个方法,该方法接受一个块并迭代一个可枚举并将该块应用于沿途的每个元素。
You'd probably want something like this:
or perhaps this way:
There are various ways to build the final string, the meat of it is that you're building a method that takes a block and iterates over an enumerable and applies the block to each element along the way.