You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Ruby on Rails中设置深色主题为默认并保留切换功能

解决方案:设置深色主题为默认并修复切换功能

1. 修复控制器中的主题切换逻辑

你的set_theme方法里有一行冗余代码导致切换失效,直接移除硬编码设置dark的语句即可:

# application_controller.rb
def set_theme
  if params[:theme].present?
    theme = params[:theme].to_sym
    # 可选:设置cookie有效期,让主题偏好持久化
    cookies[:theme] = { value: theme, expires: 1.year.from_now }
    redirect_to(request.referrer || root_path)
  end
end

2. 设置深色主题为默认值

在application.html.erb中,当用户未设置过主题cookie时,默认给body添加dark类:

# application.html.erb
<body class="<%= cookies[:theme] || 'dark' %>">
  <%= render 'shared/navbar' %>
  <%= render "shared/flashes" %>
  <%= yield %>
</body>

3. 保留导航栏切换逻辑

你的导航栏逻辑本身无问题,配合默认值后,首次访问会显示"Light Mode"选项,符合预期:

# navbar 代码
<% 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 %>

关键说明

  • 移除控制器中硬编码的cookies[:theme] = 'dark'是核心修复点,此前这行代码会覆盖用户传入的theme参数,导致浅色主题切换操作被强制重置为深色。
  • 通过cookies[:theme] || 'dark'确保首次访问的用户默认使用深色主题。
  • 给cookie添加有效期可让用户的主题偏好在下次访问时保留,提升体验。

内容的提问来源于stack exchange,提问作者jimW

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:07:33