简体   繁体   中英

RoR show elements in two columns

how can i split elements of a model into two equally sized pieces so that i can show them in two columns?

i have this:

element 1
element 2
element 3
element 4
element 5


and i want this:

element 1    element 4
element 2    element 5
element 3

split() unfortunately removes the middle element.

Array#in_groups_of is an core extension and only available in Rails. What it uses though is the each_slice method.

You could use it like this:

a = ["element 1", "element 2", "element 3", "element 4", "element 5"]
a.each_slice((a.size/2.0).ceil) { |slice| puts slice } if a.size > 0

will give you

["element 1", "element 2", "element 3"]
["element 4", "element 5"]

Note that you must check that a.size is bigger then 0 or you will get an ArgumentError exception due to invalid slice size.

as i only need to use this in rails, this worked for me:

>> a = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> a.in_groups_of( (a.size/2.0).ceil, false ) if a.size > 0
=> [[1, 2, 3], [4, 5]]

Check out Array#in_groups_of

This will slice an array in chunks of your liking.

One approach is to use jQuery. There are several plugins that can accomplish this for you.

Subsequently, after you have the two chunks, start filling up a div with the first group, once you get to the end, start the second group in a second div. Then use css to position and style the two divs beside one another.

Where are you trying to show these elements?

If it's in a view, you should not be modifying your model; your models should stay independent from your presentation.

If you want to present results on a web page, you must use html and css in your view. Even in your view, you probably won't need to "split" your elements into sub arrays.

See this page , for example. If you look at the source code, the lists are allways "one after the other", without splitting into groups. The CSS conditions how the text is positioned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM