代码之家  ›  专栏  ›  技术社区  ›  Lee Eather

我们可以在rails css.erb视图文件中使用scss(sass-rails)吗?还是这只是一个资产管道的事情?

  •  0
  • Lee Eather  · 技术社区  · 5 年前

    我想知道,我们可以在rails视图中使用scs吗,例如

    /views/home/stylesheet.css.scs.erb

    $gray-medium-light : #eaeaea;
    
    background: $gray-medium-light;
    

    我尝试更改路径格式

    <%= stylesheet_link_tag(about_me_user_path(current_user, format: :scss), media: 'all', class: "home_about_me_css") %>
    

    而且在路线上

    get    'user_profile_stylesheet/:id'  => 'users#user_profile_stylesheet',  as: :user_profile_stylesheet, :defaults => { :format => 'scss' }
    

    但rails似乎只是将格式转换回 css .

    我们能用吗 sass-rails gem会以某种方式做到这一点吗?

    谢谢。

    编辑 我在谷歌上搜索了这个,但什么也没找到。

    0 回复  |  直到 5 年前
        1
  •  1
  •   max Mike Williams    5 年前

    通过调用sass编译器,这在理论上是可能的。请注意,您希望使用css而不是scss请求。客户端没有理由需要知道文件是如何生成的。

    <%= stylesheet_link_tag(about_me_user_path(current_user, format: :css), media: 'all', class: "home_about_me_css") %>
    

    class UsersController
      def user_profile_stylesheet
        respond_to do |f| 
          f.css do
            fn = Rails.root.join('app', 'views', 'home', 'home_stylesheet.css.scss.erb')
             # expand ERB template
            sass = render_to_string(file: fn)
            # run rendered template through the sass compiler
            css = SassC::Engine.new(sass, style: :compressed).render 
            render text: css
          end
        end  
      end
    end   
    

    我不太确定这是你真正想在生产环境中做的事情,因为它要求你在响应请求时在运行时编译sass。而且,您将无法在资产管道中引用任何类似SASS函数的内容,因为这是在管道外编译的。

    这也是一场安全噩梦,因为SASS不像CSS那样只是声明性的。这可能会被用来在您的服务器上执行代码。

    无论你想做什么,都必须有一个更聪明/更简单的解决方案。