Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'dynamic CSS' in Rails

I'm new to Ruby on Rails and I'm trying to extract information I have from certain fields in a database and use them as means of styling.

For example, I have a height and width field in my 'Student' database. I wish to extract the height field content and width field content as parameters for my CSS file to set the height and width respectively of a div tag.

I am having a lot of trouble doing this. I have linked my stylesheet in the view index.html.erb by:

<%= stylesheet_link_tag 'students' %>

which is under assets/stylesheets/students.scss

I am not sure how to proceed.

like image 700
helpisgood Avatar asked Dec 07 '25 14:12

helpisgood


2 Answers

If the styling is database driven, you should not rely on sprockets which generates static stylesheets during deployment.

A simple solution is to build css content using ERB.

<style>
.students-container {
  height: "<%= @height.to_i %>px",
  width: "<%= @width.to_i %>px"
}
</style>

You can extract out the style node into a partial and reuse it in multiple templates.

like image 165
lorefnon Avatar answered Dec 10 '25 05:12

lorefnon


Seems like an inline style would work fine here. In your ERB, in your student divs, just do:

<% @students.each do |student| %>
  <div style="height: <%= student.height %>px; width: <%= student.width %>px;">
    <!-- other student stuff -->
  </div>
<% end %>

It's either this or generating a unique CSS class for every student first, then using it in each div.

like image 45
Nick Veys Avatar answered Dec 10 '25 04:12

Nick Veys