如何使用 SASS 作为 Rails 3 中视图的模板处理程序? [英] How to use SASS as a template handler for views in Rails 3?

查看:37
本文介绍了如何使用 SASS 作为 Rails 3 中视图的模板处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过根据数据库中的信息生成样式表的情况.这意味着我有一个 views/users/show.css.erb 包含如下代码:

I have situation where I generate stylesheets based on information in the database. This means I have a views/users/show.css.erb which contains code like:

a {
  color: <%= @user.favorite_color %>;
}

很公平,与 response_to { |f| 完美配合f.css } 在我的控制器中.但是现在我想在我的 CSS 中使用一些 SASS 的时髦功能,如变亮、变暗等,所以我想让 SASS 解析我的视图.但是,如果没有太多丑陋的黑客攻击,我无法弄清楚如何在我的视图中将 SASS 注册为模板处理程序.我只是不明白它是如何工作的.有没有人试过这个?

Fair enough, works perfectly with a respond_to { |f| f.css } in my controller. However now I would like to use some of SASS's sassy functions like lighten, darken etc. in my CSS, so I would like to have SASS parse my view. However I cannot figure out how to register SASS as a template handler in my views without too much ugly hacks. I just don't get how it works. Has anyone ever tried this?

我曾尝试包含 SASS 的函数模块,但无济于事.

I have tried including SASS's Functions module but to no avail.

推荐答案

我前段时间计划为动态用户主题做同样的事情.当时,我发现了一个 邮件列表回答 与您类似的问题,作者:Nathan Weizenbaum(SASS 的作者)让我回到又直又窄的路上:

I was planning of doing the same for dynamic user themes some time ago. Back then, I found a mailing list answer to a similar question to yours, by Nathan Weizenbaum (author of SASS) which got me back on the straight and narrow:

3 月 18 日上午 11:46,内森·魏泽鲍姆写道:

On Mar 18, 11:46 am, Nathan Weizenbaum wrote:

Sass 不允许动态访问 Rails 代码是有原因的 - 请参阅http://haml.hamptoncatlin.com/docs/rdoc/files/FAQ.htmlfor 的 Sass 部分简短的讨论.Sass 也相当慢,因为它只编译一次,所以这对于生产环境来说可能太慢了.

There's a reason Sass doesn't allow dynamic access to Rails code - see the Sass section ofhttp://haml.hamptoncatlin.com/docs/rdoc/files/FAQ.htmlfor a brief discussion. Sass is also fairly slow, since it's only compiled once, so this is probably far too slow for a production environment.

该链接不再有效,但 SASS 常见问题解答只有一个名为 的部分我可以在我的 Sass 文件中使用控制器中的变量吗?回答动态问题:

The link is not working anymore, but the SASS FAQ has only one section called Can I use a variable from my controller in my Sass file? which answer the dynamic question:

如果你真的,真的需要在每个请求上编译 Sass,首先确保你有足够的缓存设置.然后你可以使用 Sass::Engine 来渲染代码,使用 :custom 选项传入可以从你的 Sass 函数访问的数据.

If you really, really need to compile Sass on each request, first make sure you have adequate caching set up. Then you can use Sass::Engine to render the code, using the :custom option to pass in data that can be accessed from your Sass functions.

所以总的来说,SASS 并不是为每个请求的动态 css 生成而设计的.相反,它旨在用作生成静态 css 文件的预编译解决方案.

So in general, SASS is not designed for dynamic css generation on each request. Rather it is intended to be used as a pre compilation solution to generate static css files.

这篇关于如何使用 SASS 作为 Rails 3 中视图的模板处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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