Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing users to choose custom theme in Rails

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

like image 999
sent-hil Avatar asked Mar 06 '10 08:03

sent-hil


2 Answers

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!

like image 111
Gdeglin Avatar answered Nov 08 '22 07:11

Gdeglin


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 %>
like image 43
Alex Avatar answered Nov 08 '22 07:11

Alex