kouroubel
kouroubel

Reputation: 280

ENV variables in scss file

I would like to set the color of the navbar and jumbotron pic using environmental variables.

In my application.yml file I have

NAVBAR_COLOR: "#FF7F50"    
JUMBOTRON_PIC: 'asset-url("somePic.png")'

I have changed the custom.css.scss to custom.css.scss.erb and added the following lines

.navbar-default {
    background-color: <%= ENV["NAVBAR_COLOR"] %> ; 
}

.jumbotron{
  background-image: <%= ENV["JUMBOTRON_PIC"] %> ;
}

however, neither of the above works.

Any idea why?

Upvotes: 0

Views: 3283

Answers (2)

kouroubel
kouroubel

Reputation: 280

Regarding the updating of ENV variables you have to restart the server as indicated in one of the comments.

For the background image to load correctly, I found that the following works:

#config/application.yml
JUMBOTRON_PIC: "/assets/somePic.png"
NAVBAR_COLOR: "#1ac2ff"

#layouts/mylayout.html.erb
 <style>          
   .jumbotron{
        background-image:  url( "<%= ENV["JUMBOTRON_PIC"] %>" );
      }      

   .navbar-default {
        background-color: <%= ENV["NAVBAR_COLOR"] %> ; 
  }  
 </style>

Upvotes: 0

arieljuod
arieljuod

Reputation: 15848

.scss files are not .erb files, so <%= .... %> won't work. Add an extra .erb extension to it and be sure it's precompiled server side and not locally and it will work only once at the moment of precompiling it.

Personally I wouldn't do this that way. For this I would just render that inside my template:

#layouts/mylayout.html.erb

...
<head>
  <style>
    .navbar-default {
      background-color: <%= ENV["NAVBAR_COLOR"] %> ; 
    }
    .jumbotron{
      background-image: <%= ENV["JUMBOTRON_PIC"] %> ;
    }
  </style>
</head>
...

Assets gets precompiled once and then delivered respond fast, it's not a good idea to make them depend on env variables and even worse idea if you plan to update that variable after precompiling it.

Upvotes: 1

Related Questions