简体   繁体   中英

How do I show two different partials on every other pageview?

I am using the cycle Rails method - largely because I couldn't think of another way.

All I am doing, is in my controller declaring this:

@banner_cycle = [1,2]

And in my view, doing this:

<div class="hidden-sm hidden-xs text-center">
    <% @banner_cycle.each do |x| %>
        <%= cycle(render "shared/banner_728x90", render "shared/banner_970x250") %>
    <% end %>               
</div>

This is the error I am getting though:

SyntaxError at /posts/another-awesome-test
syntax error, unexpected tSTRING_BEG, expecting keyword_do or '{' or '('

Unless it's changed or I've forgotten cycle doesn't work across page views. It only works for the current view/page-load. If you really want to alternate page views you'll have to keep state somewhere on the server. Or, if you're okay alternating per user you can track it in a session. Say something like...

In your controller action:

session[:banner_cycle] = session[:banner_cycle].to_i + 1

The .to_i is to protect against nil.

In your view:

<div class="hidden-sm hidden-xs text-center">
    <% if session[:banner_cycle].even? %>
        <%= render "shared/banner_728x90" %>
    <% else %>
        <%= render "shared/banner_970x250" %>
    <% end %>               
</div>

I suppose an aggressive user could overflow the maximum integer value, but I'm not going to worry about that here.

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