In my application I do each_slice
and then each_with_index
because of some stuff I'm doing in my application.
My current code is like this:
- @images.each_slice(@album.images_per_page <= 2 ? 1 : 2) do |group|
- group.each_with_index do |img, i|
.col-md-2
/* Ads Left */
.col-md-7
= image_tage img.image_url(:thumb)
.col-md-3
/* Ads Right */
Usually I show 4 images on every page. The first 3 will have ads inside .col-md-2
& .col-md-3
. What I want to achieve is to add different ads-codes/type for each element.
For instance, First image would have 300x250 tag , second image 300x600 and third would have content-type ads (Taboola) and not showing any ads after these 3.
I tried: (Ex. 1)
- if i == 0
%h1 300x250
- elsif i == 1
%h1 300x600
- elsif i == 2
%h1 Taboola
and (Ex. 2)
- if i+1 == group.length
%h1 i+1 = group.length
But I don't get what I'm looking for. Ex.1 takes every 1 element and adds 300x250 & every 2nd element and adds 300x600 , So I don't get Taboola and gets double of 300x250 & 300x600 while Ex.2 takes every 2nd element and adds only 300x250 .
Ex.1 results becomes this:
Image 1 => 300x250
Image 2 => 300x600
Image 3 => 300x250
Image 4 => 300x600
Ex.2 results becomes this:
Image 1 => /* Nothing */
Image 2 => 300x250
Image 3 => /* Nothing */
Image 4 => 300x250
How can I achieve so I can choose what ad I want to show on each element?
Result I'm looking for:
Image 1 => 300x250
Image 2 => 300x600
Image 3 => Taboola
Image 4 => /* Nothing */
Hope I could explain what I'm looking for.
The goal should be to leave as few logic as possible in views. Complex logic should be done in model/controller/helpers.
Here's a possibility with zip
:
@images = %w(imageA imageB imageC imageD)
params = [
['300x250','r1'],
['300x600','r2'],
['Taboola','r3']
]
@images.zip(params).each_with_index do |(image, param), i|
left, right = param
puts "Image : #{image}"
puts "ParamL: #{left}"
puts "ParamR: #{right}"
puts "Index : #{i}"
puts "Even? : #{i.even?}"
puts
end
It outputs :
Image : imageA
ParamL: 300x250
ParamR: r1
Index : 0
Even? : true
Image : imageB
ParamL: 300x600
ParamR: r2
Index : 1
Even? : false
Image : imageC
ParamL: Taboola
ParamR: r3
Index : 2
Even? : true
Image : imageD
ParamL:
ParamR:
Index : 3
Even? : false
It seems to be enough information for what you want to do.
Also, you're calling each_slice
with either 1 or 2 as parameter. each_slice(1)
is basically useless, each_slice(2)
would just split your array in pairs. Checking if id
is odd or even should give you just as much information, without needing another nested block.
each_slice(2)
is also the reason why your index stays equal to 0
or 1
. It cannot be equal to 2, so your Taboola
case never happened.
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.