允许用户在 Rails 中选择自定义主题
我想让我的用户能够从 5 种不同的布局中选择其公共页面的显示方式。我假设根据布局我需要 5 个不同的 css 文件,然后需要将其传递到 stylesheet_link_tag
我只知道如何使用 if then 语句来做到这一点。我不认为这是最好的方法。任何帮助...也可以做到吗?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该将用户选择的布局存储在会话变量中(最简单,但当用户清除 cookie 或使用不同的计算机时会丢失)或数据库中。
假设样式表有五个名称,每个名称对应一种颜色:
将这些文件放置在
public/stylesheets 中。
将用户对样式表的选择存储到
session[:style]
像这样的变量:只要用户不清除他们的cookie,这个值就会一直存在。
如果您的布局中尚不存在 application.erb 文件,请创建一个 application.erb 文件。该文件中的代码将为您网站上的每个模板呈现。它应该包含类似
<%= yield %>
的行。在此文件中放置以下内容:<%=stylesheet_link_tag session[:style]+'_stylesheet'%>
就是这样!
祝你好运!
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:
Place these files inside of
public/stylesheets.
Store the user's choice of stylesheet into the
session[:style]
variable like so: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!
首先,尝试将“主题”字段添加到用户的模型中(使用迁移)。
然后在视图中添加一些链接(用户设置):
link_to 'Change to green theme', :controller => “用户”,:操作=> “设置主题”,:id => "green"
控制器:
公共配置文件的控制器:
布局:
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:
Public profile's controller:
layout: