简体   繁体   中英

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.

I am wanting users to be able to select a few CSS attributes to personalize their own theme when they login. 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. Jquery gives a simple way to do that, and you can store the styles on a column in your model.

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

rails g migration addstylestousers styles:string

in your 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!".

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. However, nesting it's getting yourself into more problem, I don't think it's worth it at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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