1

How to create different view modes. Like a visitor can choose list or box view.

2

2 Answers 2

1

It depends how much these views are similar, what I would do is to create partials for each view and then in the main view I call the right one depending on the property. Say you have a function in application_helper which_view in your index you can write something like this:

<!-- your index -->
<%= render which_view == :box ? 'index_box' : 'Index_list' %>

I prefer the previous, but if you have few changes you can go for something like:

<% if session[:view_type] == 'box' %>

  <!-- box content -->

<% else %>

  <!-- list content -->

<% end %>

** EDIT **

make the action:

  # application_controller.rb
  def set_view_type # TODO: refactor
    session[:view_type] = params[:view_type]
    redirect_to :back
  end

set your routes:

  # routes.rb
  match '/set_view_type' => 'application#set_view_type', :as => :set_view_type

write your form:

  <!-- _view_type_selection.html.erb -->
  <%= form_tag set_view_type_path do %>

    <%= radio_button_tag :view_type, :box, session[:view_type] == 'box' %>

    <%= radio_button_tag :view_type, :list, session[:view_type] == 'list' %>

    <%= submit_tag 'select' %>

  <% end %>

Not best practice but it works!

Sign up to request clarification or add additional context in comments.

1 Comment

How to create the helper method ?
1

I almost agree with ecoologic. Instead of second solution i would use something like case statement in controller which decides what template should be rendered.

How to create the helper method ?

Add it into <controller_name>_helper file

3 Comments

Ah yes! this is better, you avoid to render the switcher that renders the partials! - Maybe you have a good idea on how to store the value, I don't like it very much
I don't know whole Rails beginner's idea, but instead of storing it, i would rather see it in url. So if i send a link for some interesting page, it looks same as on my screen and i can navigate recipient on that page. Or i can send that link directly with anchor, which could be in one layout, byt it does not in another. It's also better for bookmarking, etc... I dont know any english example but look for this tv.seznam.cz/radkovy-program and this tv.seznam.cz/sloupcovy-program . I can send one of these links and say "Look at the second line/column"
I understand your pov, I personally don't like to store params in url, but thinking about a guest option it makes perfectly sense

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.