如何使用 SASS 作为 Rails 3 中视图的模板处理程序?

发布于 2024-12-28 03:03:47 字数 368 浏览 0 评论 0原文

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

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

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

我尝试过包含 SASS 的 Functions 模块但无济于事。

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 %>;
}

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无戏配角 2025-01-04 03:03:47

不久前我计划对动态用户主题做同样的事情。当时,我发现了一个邮件列表回答 让我回到了正题:

3 月 18 日上午 11:46,Nathan Weizenbaum 写道:

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

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

如果您确实非常需要针对每个请求编译 Sass,请首先确保您已设置足够的缓存。然后,您可以使用 Sass::Engine 来呈现代码,并使用 :custom 选项传入可从 Sass 函数访问的数据。

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

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:

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

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.

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:

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文