Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create dynamic CSS in Rails?

what is the best/most efficient way of creating dynamic CSS with Rails. I am developing an admin area on a site, where I would like a user to be able to customize the style of their profiles(Colour mostly), which will also be saved.

Would you just embed ruby script in the css file? Would you need to change the file extension from css?

Thanks.

like image 836
Matt Avatar asked Aug 24 '10 13:08

Matt


People also ask

Can you dynamically change CSS?

If you want to change the CSS styles dynamically you'll have to attach this portion of code to some event. For example, if you want to change the styles of your element when clicking on a button, then you have to first listen to the click event and attach a function containing the previous code.

What is dynamic CSS?

This is a collection of methods which give you the ability to query the stylesheets collection in a document, add and remove rules, and dynamically create new sheets.

How do I change dynamic style in CSS?

color = "red"; you can apply the style change dynamically. Below is a function that turns an element's colour to red when you pass it the element's id . You could also use setAttribute(key, value) to set a style on an element. For example, you could set the colour of an element to red by calling element.


1 Answers

In Rails 3.1, you can have your stylesheets pre-processed by erb.

Now let's say you have some dynamic styling called dynamic.css.scss.erb (the .erb at the end is important!) in app/assets/stylesheets. It will be processed by erb (and then by Sass), and as such can contain stuff like

.some_container {
    <% favorite_tags do |tag, color| %>
    .tag.<%= tag %=> {
        background-color: #<%= color %>;
    }
    <% end %>
}

You can include it like any stylesheet.

How dynamic should it be?

Note that it will be only processed once, though, so if the values changes, the stylesheet won't.

I don't think there is a super efficient way to do have it completely dynamic yet, but it is still possible to generate the CSS for all requests. With this caveat in mind, here's a helper for that in Rails 3.1:

  def style_tag(stylesheet)
    asset = YourApplication::Application.assets[stylesheet]
    clone = asset.class.new(asset.environment, asset.logical_path, asset.pathname, {})
    content_tag("STYLE", clone.body.html_safe, type:"text/css")
  end

Here's how to use it:

First, copy the above helper in app/helpers/application_helper.rb.

You can then include it in your page as follows:

<% content_for :head do %>
  <%= style_tag "dynamic.css" %>
<% end %>
The rest of your page.

Make sure that your layout uses the content :head. For example, your layout/application.html.erb could look like:

...
<HEAD>
  ....
  <%= yield :head %>
</HEAD>
...

I found this out thanks to this post.

like image 94
Marc-André Lafortune Avatar answered Oct 06 '22 02:10

Marc-André Lafortune