Dynamically output sass file through asterisks

I want the helper to display some variables in a template .scss.erbthat uses the image-url()sass function :

// template.scss.erb

#<%= id %> {
  background-image: image-url('<%= image_file %>');
}

So far, the ERB part has been easy:
(using this answer )

vars_binding = OpenStruct.new(
                 id:         'foo', 
                 image_file: 'foo.jpg'
               ).instance_eval { binding }

template = File.read('path/to/template.scss.erb')

rendered_sass = ERB.new(template).result(vars_binding)

Running this code is sassnow equal to:

#foo {
  background-image: image-url('foo.jpg');
}

However, the next time I try to run:

css = Sass::Engine.new(
  rendered_sass,
  syntax:     :scss,
  cache:      false,
  load_paths: view_context.assets.paths,
  read_cache: false,
  style:      :compressed
).render

He returns

NoMethodError: undefined method `[]' for nil:NilClass
from …/sprockets-3.2.0/lib/sprockets/sass_processor.rb:267:in `sprockets_context'

because the call Sass::Enginedoes not provide a Sprockets context.

If I remove image-url()from the template .scss.erband replace it with native url(), it will display correctly as CSS, no problem.

So, how do I display this pattern in the context of asterisks?

+4
source share
2 answers

: :sprockets Sass::Engine.new.

css = Sass::Engine.new(
  rendered_sass,
  syntax:     :scss,
  cache:      false,
  load_paths: view_context.assets.paths,
  read_cache: false,
  style:      :compressed,

  # The key ingredient…
  sprockets:  {
    context:     view_context,
    environment: view_context.assets
  }
).render

, view_context , ActionView::Base.new

+7

All Articles