下面的代码将生成一个由13页标题组成的数组(我相信这是一个数组)。我希望标题0-5是在它自己的div,6-8在第二个div和9-12在第三个,下拉菜单。我在这里找不到这个确切的问题/答案。
<% @cms_site.pages.root.children.published.each. do |page| %>
<%= link_to page.label, page.full_path %>
<% end %>谢谢!
发布于 2013-09-21 19:10:37
您尝试了什么?#each对于这个案例不是一个很好的用途。您可能需要将它分成3个不同的循环,如下所示:
<% @cms_site.pages.root.children.published[0,5].each do |page| %>
<%= link_to page.label, page.full_path %>
<% end %>
<% @cms_site.pages.root.children.published[6,8].each do |page| %>
<%= link_to page.label, page.full_path %>
<% end %>
<% @cms_site.pages.root.children.published[9,12].each do |page| %>
<%= link_to page.label, page.full_path %>
<% end %>编辑--似乎您有一些逻辑问题,至少首先尝试一下是明智的。
上面的代码应该可以工作,但并不是很枯燥,它可以被提取到一个帮助方法中,它使用迭代器的章节,或者可能使用不同的迭代器(例如each_with_index),并处理块中每个索引的检查。做你要做的事有很多种方法。
发布于 2013-09-21 19:24:31
基本上,如果您处理的是数组,并且每次都想从数组中获取完全相同的元素,那么下面是如何分割它的方法:
# Your Array
elements = [1,2,3,4,5,6,7,8,9,10,11,12]
# This will give you three arrays inside one array. The first will be first six
# elements starting from 0, the second is 3 elements starting from 6, etc.
arrays = [ elements[0,6], elements[6,3], elements[9,3] ]现在,您可以遍历数组并重用代码来生成所需的代码。
arrays.each do |ar|
# Now render for each array as you please, and reuse the same code.
endhttps://stackoverflow.com/questions/18936455
复制相似问题