Is it possible to include erb in scss files? scss.erb?

I would like to have different image locations for dev and build environments.

Is there a way to run ruby or use a varialbe in an scss file?

I know it’s possible to check the current environment via settings.build?

I tried to use style.scss.erb but I would get an error.

I guess I could load different css files by using an if statement in slim but it would be cleaner to just use logic in the scss file.

Has anyone successfully done this? Or, is there an alternative, equally efficient approach?

Have you tried config.rb?


configure :development do
  set :images_dir, 'images_dev'
end

configure :build do
  set :images_dir, 'images_prod'
end

I’ve checked on a fresh empty project in MM 3.3.5 and it works for me. You must then use image-path or image-url helpers in scss files, instead of plain strings:

background: #d4d4d4 image-url("background.png");

Additionally, I don’t know if this is officially supported and tested to change this config var per environment.

1 Like

Ha! @komor72 beat me to it. Alas I don’t know enough about SCSS to guess how to pass environment variables from middleman into it.

Only specific helpers are available in the clean-Sass file – those brought by Compass (and Sprockets?). But I’m puzzled why the .scss.erb approach didn’t work out. I’m pretty sure I read about such an approach.

One more thing, @andreimoment. You will have the build folder polluted with images_dev content, which will be copied over during the build process. So this is kinda workarond, not a solution. You can automatically clean it with an after_build hook.

after_build do |builder|
  print "After_build fixes... "
  system("rm -rd #{config[:build_dir]+'/images_dev'}")
  puts "done."
end

Someone more eloquent could propose a solution using builder commands.

@komor72 / Rafal, thank you for the extensive explanation and the number of options you provided including the scss erb fix (which targets rails but is probably applicable to middleman, too – by someone who knows what they’re doing).

If I understand correctly, you propose that I set the :images_dir in config.rb and then use compass’ image-url helper in the SCSS file. Some digging in compass documentation cleared my confusion around the origin of :images_dir: http://compass-style.org/help/documentation/configuration-reference/

This makes sense, and I’ll try it out.

Meanwhile, I added a variable to my _settings.css.scss

$photos-url: "http://cdn.xyz.com/img"; // build
// $photos-url: "../img";              // test

which I manually switch before building. At this point, a day before launch, my images live in the CDN anyway, so it’s actually good that if I change an image on dev, I won’t see the changes unless I change the CDN, too.

Thank you for your response, this is a wonderful community.