通过链轮动态渲染一个sass文件 [英] Dynamically render a sass file through sprockets

查看:50
本文介绍了通过链轮动态渲染一个sass文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从助手那里在使用 image-url() sass 函数的 .scss.erb 模板中呈现一些变量:

I want, from a helper, to render some variables in a .scss.erb template that makes use of the image-url() sass function:

// template.scss.erb

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

到目前为止,ERB 部分很简单:
(利用这个堆栈溢出答案)

So far, the ERB part has been easy:
(leveraging this stack overflow 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)

运行该代码,sass 现在等于:

Running that code, sass is now equal to:

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

但是,当我下次尝试运行时:

However, when I next 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

它返回

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

因为对 Sass::Engine 的调用不提供链轮上下文.

because the call to Sass::Engine doesn’t provide a Sprockets context.

如果我从 .scss.erb 模板中删除 image-url(),并用原生 url() 替换它,然后它将正确呈现为 CSS,没问题.

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

那么如何在 sprockets 上下文中呈现此模板?

推荐答案

经过类似问题,经过大量反复试验,我找到了我的解决方案:调用:sprockets哈希>Sass::Engine.new.

After digging through a similar question, and a lot of trial and error, I found my solution: I have to supply a :sprockets hash when calling 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

It should be noted that view_context was passed from a view file, but it could have also been ActionView::Base.new

这篇关于通过链轮动态渲染一个sass文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆