gpt4 book ai didi

ruby-on-rails - rails : Render collection partial: Getting size of collection inside partial

转载 作者:行者123 更新时间:2023-12-04 00:56:42 27 4
gpt4 key购买 nike

我有一组我想用部分渲染的项目:

@items = ['a','b','c']

<%= render :collection => @items, :partial => 'item' %>

我想用升序对元素进行编号。所以输出应该是:
3: a
2: b
1: c

我知道 rails 在部分内部提供了一个计数器,所以如果我想对项目进行降序编号,我可以创建以下部分:
<%= item_counter %>: <%= item %>

这给了我
1: a
2: b
3: c

但是对于升序数字,我需要项目总数,我可以提供局部到局部:
<%= render :collection => @items, :partial => 'item', :locals => {:total => @items.size} %>

然后在部分:
<%= total - item_counter %>: <%= item %>

但对我来说感觉就像重复,因为 render 方法已经知道集合的大小。

除了使用局部变量之外,真的没有办法在部分中获取集合的项目总数吗?

最佳答案

以下是可能的 自 Rails 4.2 版起 :

在部分内部,您可以访问名为 collection_iteration 的函数/变量.调用 collection_iteration.size会给你总数。

来自 changelog :

The iteration object is available as the local variable #{template_name}_iteration when rendering partials with collections.

It gives access to the size of the collection being iterated over, the current index and two convenience methods first? and last?.

关于ruby-on-rails - rails : Render collection partial: Getting size of collection inside partial,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13397848/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com