简体   繁体   English

Ruby on Rails中用户的个人CSS样式表

[英]User's Personal CSS Stylesheet in Ruby on Rails

I have looked around but I can't find a lead on what I need to do to make the following possible: 我环顾四周,但无法找到实现以下目标所需的方法:

This question assumes I have all model controllers working properly and the named CSS attributes are defined in the default stylesheet. 这个问题假设我所有模型控制器都正常工作,并且命名的CSS属性在默认样式表中定义。

I am wanting users to be able to select a few CSS attributes to personalize their own theme when they login. 我希望用户能够在登录时选择一些CSS属性来个性化自己的主题。 The basics attributes would be the "body" and "page-wrapper" colour. 基本属性是“正文”和“页面包装”颜色。 (foreground) (前景)

I am wanting them to be able to select these attributes (from a form?) in the user's edit page. 我希望他们能够在用户的编辑页面中选择这些属性(从表单?)。 (which is already created) (已创建)

Any ideas as to how I could make this work or a good lead in the right direction? 关于如何进行这项工作或在正确的方向上取得良好的领导的任何想法?

Thanks for your help. 谢谢你的帮助。

I think the best approach is via javascript, generating an style tag on the head with the desired styles. 我认为最好的方法是通过javascript,在头上生成具有所需样式的样式标签。 Jquery gives a simple way to do that, and you can store the styles on a column in your model. jQuery提供了一种简单的方法,您可以将样式存储在模型的列中。

Something like this: 像这样:

class User
  attr_accesible :styles

view.erb 视图

<script>
  // Assume the @styles attr has something like "body { background-color: #567;}"
  $('head').append($('<style>').html('<%= @user.styles %>'))
</script>

@styles will be another column in your model, so you should add it with a migration @styles将是模型中的另一列,因此您应该在迁移时添加它

rails g migration addstylestousers styles:string

in your form.erb 在你的form.erb中

<%= f.label :styles %>
<%= f.text_field :styles %>

I think it's simple enough for the user to put the css style here as long as you give him enough tips like "add body { background-color: red } in this field to make you background red!". 我认为,只要您给他足够的提示,例如“在此字段中添加body { background-color: red }来使背景变成红色!”,用户就可以轻松地将css样式放在此处。

About serialization, consider this . 关于序列化,请考虑一下

If you want to nest the styles, then the script will be 如果要嵌套样式,则脚本将是

//Lets say that the user stored on @bgcolor and @fgcolor only css color codes, like '#222' or 'blue'
var bgc = '<%= @user.style.bgcolor %>'
var fgc = '<%= @user.style.fgcolor %>'
var style = 'body { background-color: ' + bgc + '; foreground-color: ' + fgc + ' }'
$('head').append($('<style>').html(style))

Remember that relationship should be User has_one :style on this case. 请记住,在这种情况下,关系应为User has_one :style However, nesting it's getting yourself into more problem, I don't think it's worth it at all. 但是,嵌套它会使您陷入更多问题,我认为这根本不值得。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM