You don't need to migrate columns, have a current user, or add new stylesheets.
Here's how it works on my website:
Live Demo - try to click yourself!
Here's how to do it:
- Set a
body
class
and create links to selecting atheme
:
# application.html.erb
<body class="<%= cookies[:theme] %>">
<% if cookies[:theme] == "light" %>
<%= link_to "go dark", root_path(theme: "dark") %>
<% else %>
<%= link_to "go light", root_path(theme: "light") %>
<% end %>
<%= yield %>
</body>
- Persist
theme
incookies
:
# application_controller.rb
before_action :set_theme
def set_theme
if params[:theme].present?
theme = params[:theme].to_sym
# session[:theme] = theme
cookies[:theme] = theme
redirect_to(request.referrer || root_path)
end
end
- Update your css file accordingly:
# application.scss
body.light {
color: black;
background-color: white;
}
body.dark {
color: white;
background-color: black;
}
That's it! Now you can customize your css
as you like.
That's it!ðŸ¤
Liked this article? Please follow me! It will really motivate me to post more fun stuff!
Top comments (2)
nice one, works well
very nice stuff here, I used it on one of my websites and it works good