ruby-on-railsrubyerbdarkmode

Set dark theme to default in ruby on rails


we created an dark theme for our website and we like to better than the light theme. That is why we want to set the dark theme to default, but it should be possible to switch from dark to light theme using the toggle button.

Could someone help me with that? I would appreciate it!

This is our code:

/application.html.erb
<!DOCTYPE html>
  <head>
    <title>CollectiverseForum</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
    <%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>
  </head>

  <body class="<%= cookies[:theme] %>">
    <%= render 'shared/navbar' %>
    <%= render "shared/flashes" %>
    <%= yield %>
  </body>
</html>
/application_controller.rb
def set_theme
  if params[:theme].present?
    cookies[:theme] = 'dark' #switch color mode doesnt work because of this code
    theme = params[:theme].to_sym
    cookies[:theme] = theme
    redirect_to(request.referrer || root_path)
  end
end
navbar code 
<% if cookies[:theme] == "light" %>
   <%= link_to "Dark Mode", root_path(theme: "dark"), class:"dropdown-item dropdown__list static__text" %>
<% else %>
   <%= link_to "Light Mode", root_path(theme: "light"), class:"dropdown-item dropdown__list static__text" %>
<% end %>

Solution

  • I will assume that setting dark or light as body HTML class does toggle between dark and light mode and that only the default and switch logic is not working.

    I would change the set_theme in the application_controller.rb to this:

    before_action :set_theme
    
    private
    
    def set_theme
      # default to 'dark' if not already set
      cookies[:theme] ||= 'dark'      
    
      # switch theme if set in the params
      cookies[:theme] = params[:theme] if params[:theme].in? ['dark', 'light']
    end
    

    And would build the toggle in the navbar like this:

    <% if cookies[:theme] == "light" %>
      <%= link_to "Dark Mode", url_for.merge(theme: "dark"), class: "dropdown-item dropdown__list static__text" %>
    <% else %>
       <%= link_to "Light Mode", url_for.merge(theme: "light"), class: "dropdown-item dropdown__list static__text" %>
    <% end %>
    

    Which would render the same page (not the root_path) but with the changed theme.