cycle() an image_tag

Deadly 提交于 2019-12-11 18:05:47

问题


I'm want to display different image version:

first article: big banner

second: small banner that float to right/left

so, first thing: use cycle() but dont work:

= cycle(image_tag(banner_big), image_tag(banner_small)

or

= image_tag(cycle(banner_big_path, banner_small_path))

Only first image is displayed

There's a proper way to make one like that ?


回答1:


Your problem is that rails is expecting you to call cycle with the same set of strings each time. At the moment you're passing a different pair of strings to each call to cycle, so rails resets the cycle each time. New cycles always start with their first value, hence the result you describe.

Assuming your articles had methods called small_path, big_path, something like

article.send(cycle("big_path","small_path"))

Should return alternate image paths.




回答2:


You can make use of the session facility to store indexes there and use those. For instance:

# application_helper.rb
def session_banner_index
  session[:banner_index] || 0
end

def session_banner(*list)
  list[session_banner_index % list.length]
end

# application_controller.rb
def increment_session_banner_index!
  session[:banner_index] = (session[:banner_index] || 0) + 1
end

These helper methods approximate the interface you were asking for:

 = image_tag(session_banner(banner_big, banner_small))


来源:https://stackoverflow.com/questions/9913550/cycle-an-image-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!