如何访问 ruby 数组中的第 n 个元素?具体来说,是一个 will_paginate 集合
我正在使用 ruby on Rails 和 will_paginate 将帖子输出到如下页面:
<div class="posts">
<% render @posts %>
</div>
假设我想更改此页面,以便在不同的 div 中渲染一些帖子: <% 渲染 'posts/post', :post => #集合中的第一个元素%>
<div class="second_post">
<% render 'posts/post', :post => #the second element in the collection %>
</div>
</div>
<div class ="lower_container">
<div class="posts">
#may have to run a loop for this last one, to render all the rest of posts. How?
<% render 'posts/post', :post => #all other posts %>
</div>
</div>
具体来说,我知道我可以使用 @post.first 作为第一个元素,但不知道第二个(或第三个或第四个元素)。当然,我的编程背景让我想做@post(n),其中n是我想要访问的元素的索引。这在红宝石中不起作用。
仅供参考:帖子集合是在控制器中创建的:
@posts = Post.paginate(:page => params[:page])
有谁知道我如何最好地实现这个目标?我知道这可能看起来很不传统,但对于 html/UI 方面,我真的想做这样的 div。
I am using ruby on rails and will_paginate to output posts to a page like this:
<div class="posts">
<% render @posts %>
</div>
Let's say I want to change this page so that I render some posts in different divs:
<% render 'posts/post', :post => #the first element in the collection %>
<div class="second_post">
<% render 'posts/post', :post => #the second element in the collection %>
</div>
</div>
<div class ="lower_container">
<div class="posts">
#may have to run a loop for this last one, to render all the rest of posts. How?
<% render 'posts/post', :post => #all other posts %>
</div>
</div>
Specifically, I know I could use @post.first for the first element, but don't know about the second (or third, or fourth elements). Naturally, my programming background makes me want to do @post(n) where n is the index of the element I want to access. This doesn't work in ruby.
FYI: The post collection is created in the controller by:
@posts = Post.paginate(:page => params[:page])
Does anyone know how I would best accomplish this goal? I know it may seem unconventional, but for the html/UI aspects I really want to do have the divs like this..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的部分中,您可以调用:
或_counter
Inside your partial you can call:
Or
<partial_name>_counter
您可以使用 CSS3 的 nth-child 选择器来定位特定的 div。例如,如果您的代码如下所示:
那么您可以像这样定位第一个和第二个
:
jQuery 也可以以相同的方式选择它们,并根据需要向它们添加类:
更新:
好的,在您回复后,我建议在迭代您的集合时使用each_with_index辅助方法,如下所示:
或者您可以使用像这样的Ruby开关,因为它们很漂亮:
希望这有帮助:)
You could use CSS3's nth-child selectors to target specific div's. For example, if your code looked like:
Then you can target the first and second
<div>
like this:jQuery also can select them the same way, and add the classes to them if you require it:
Update:
Okay, after your response I'd suggest using the each_with_index helper method when iterating through your collection, like so:
Or you could use a Ruby switch like so, as they're pretty:
Hope this helps :)