Rails:渲染集合部分:获取部分内部集合的大小 [英] Rails: Render collection partial: Getting size of collection inside partial

查看:47
本文介绍了Rails:渲染集合部分:获取部分内部集合的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a collection of items I want to render with a partial:

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

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

我想用升序数字给元素编号.所以输出应该是:

and I want to number the elements with ascending numbers. So the output should be:

3: a
2: b
1: c

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

I know rails provides a counter inside the partial, so if I wanted to number the items descending, I could create the following partial:

<%= item_counter %>: <%= item %>

这给了我

1: a
2: b
3: c

但是对于升序数字,我需要项目的总数,我可以提供局部到局部:

But for the ascending numbers, I need the total number of items, which I could provide with a local to the partial:

<%= render :collection => @items, :partial => 'item', :locals => {:total => @items.size} %>

然后在部分:

<%= total - item_counter %>: <%= item %>

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

But it feels to me like repetition, because the render method already knows about the size of the collection.

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

推荐答案

以下是可能的自 Rails 4.2 版:

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

Inside the partial you have access to a function/variable called collection_iteration. Calling collection_iteration.size will give you the total.

来自变更日志:

迭代对象可用作局部变量#{template_name}_iteration 使用集合渲染部分时.

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

它可以访问正在迭代的集合的size,当前 index 和两个方便的方法 first?last?.

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

这篇关于Rails:渲染集合部分:获取部分内部集合的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆