[英]Rails partials and HAML
I have a ajax method that renderes a @collection of users. 我有一个呈现用户@collection的ajax方法。 This code is from the users partial.
这段代码来自用户部分。 Now what I need to do is wrap a ul tag around the 3 li tags for every third object.
现在,我需要为每个第三个对象在3个li标签周围包裹一个ul标签。 How do I do this with HAML?
我该如何使用HAML? I can't just add the %ul tag to "when 1" - because HAML closes the tag when that object has been rendered.
我不能只将%ul标记添加到“ when 1”(因为1个对象被渲染后HAML会关闭该标记)。
-case user_counter + 1
-when 1
%li.first
@user.login
-when 2
%li
@uer.login
-when 3
%li.last
@user.login
This is the result I am looking for: 这是我要寻找的结果:
<ul>
<li>user1</li>
<li>user2</li>
<li>user3</li>
</ul>
<ul>
<li>user4</li>
<li>user5</li>
<li>user6</li>
</ul>
etc. 等等
I think you want each_slice
. 我认为您需要
each_slice
。 It splits an Enumerable into groups of a specified size. 它将一个Enumerable分成指定大小的组。 You could do something like:
您可以执行以下操作:
- @collection.each_slice(3) do |slice|
%ul
%li.first= slice[0].login
%li= slice[1].login
%li.last= slice[2].login
This should be functionally equivalent to Chuck's answer, just a tad shorter. 这在功能上应该等同于Chuck的答案,只是短了一点。
I prefer the simplicity in Chuck's answer, but this does work as well. 我更喜欢Chuck的回答中的简单性,但这也可以。
- @collection.each_slice(3) do |slice|
%ul
- slice.zip([:first,nil,:last]).each do |user, klass|
%li{:class => klass}= user.login
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.