views:

239

answers:

2

I want to give my users the ability to choose how their public page is displayed from 5 different layouts. I assume I'll need 5 different css files according to layout and then need to pass that into stylesheet_link_tag

I know only how to do it using if then statements. I don't suppose that is the best way. Any help...also could it be done?

Thanks

+5  A: 

You should store the layout that the user has chosen in the session variable (easiest, but lost when the user clears cookies or uses a different computer), or in your database.

Lets say the stylesheets have five names, each corresponding to a color:

blue_stylesheet.css
green_stylesheet.css
red_stylesheet.css
orange_stylesheet.css
white_stylesheet.css

Place these files inside of public/stylesheets.

Store the user's choice of stylesheet into the session[:style] variable like so:

session[:style] = 'green'

This value will persist for as long as the user does not clear their cookies.

Create an application.erb file in your layouts if one does not already exist. The code in this file will be rendered for every template on your site. It should contain a line like <%= yield %>. In this file place the following:

<%=stylesheet_link_tag session[:style]+'_stylesheet'%>

That's it!

Good luck!

Gdeglin
I'm sorry I didn't state the question properly. I meant let user choose a theme that will persist for their page no matter who visited their page, not just for them. But, <%=stylesheet_link_tag session[:style]+'_stylesheet'%> is what I was looking for. I guess I should allow user to set preference in the profile and then just replace [:style] with @user.theme?Will that work?Thanks
Senthil
+1  A: 

First, try to add 'theme' field to user's model (using migrations).

Then add some links in a view (user's settings):

link_to 'Change to green theme', :controller => "user", :action => "set_theme", :id => "green"

Controller:

def set_theme
  # don't forget to check, is there a theme with such params
  current_user.update_attributes :theme => params[:id]
end

Public profile's controller:

def public_profile
  @theme = 'default'
  user = User.find(params[:user_id]) # profile's owner
  @theme ||= user.theme # overriding default theme to custom one
end

layout:

<%=stylesheet_link_tag @theme %>
FancyDancy