如何访问 Sass 中的 Rails 对象?
在 Rails 3.1.0 项目中,我的公司具有一些可自定义的属性,例如背景颜色和链接颜色。我希望能够像这样设置一些 Sass 变量:
$background_color: <%= @company.background_color %>
$link_color: <%= @company.link_color
...
这不起作用,因为当 Sass 执行其操作时,@company
为零。我不知道如何以动态的方式解决这个问题(可以创建公司,可以更改颜色,并且视图可以立即更新)。有什么建议吗?
In a Rails 3.1.0 project, I have Companies with a few customizable attributes like background_color and link_color. I want to be able to set some Sass variables like so:
$background_color: <%= @company.background_color %>
$link_color: <%= @company.link_color
...
This doesn't work because @company
is nil when Sass does its thing. I'm not sure how to go about solving this in a way that's dynamic (companies can be created and colors can be changed and the views update immediately). Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(4)
好吧,如果您指的是动态对象,例如通过控制器加载的模型,那么您实际上不能,至少不是很容易。这是因为与 HTML ERB 模板不同,SASS 模板通常渲染一次并静态提供服务,除非代码发生变化或者通过 rake 重新预编译(取决于您的环境配置)。但是您可以访问一些辅助方法、全局对象,并通过使用“erb”扩展名重命名文件来使用一些 ruby,例如 application.css.scss.erb
。请参阅
如果您需要基于动态加载对象的样式,例如模型,您可以...
- 在模板中逐字编写 CSS 样式
- 动态编译样式表。请参阅此处最受好评的答案:如何在 Rails 中创建动态 CSS 对于某些用例,
- 您可以通过利用 Rails/SASS 的导入路径层次结构来完成相同的操作(即 SASS
@import 'partial_name_with_no_path'
将搜索导入 SASS 文件文件夹首先,然后回退到顶层 - 您也可以配置它)。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我立即想到了几种方法:
@import
提供该 CSS。通过控制器提供样式表非常简单,因此无需多说。这可能有点丑陋和麻烦。
对于第二个,您需要添加几个额外的 CSS 类:
然后任何需要使用自定义背景颜色的元素都需要其常用的 CSS 类和
custom-bg
;其他可配置值也需要类似的诡计。要提供自定义 CSS,您可以使用标准 ERB 部分将还有 JavaScript。您需要某种方法来识别需要调整颜色的元素,然后直接调整它们,如下所示:
I can think of a couple approaches off the top of my head:
@import
.Serving your stylesheet through a controller is pretty straightforward so there's not much to say. This might be a bit ugly and cumbersome.
For the second one, you'd add a couple extra CSS classes:
Then any element that need to use the custom background color would need their usual CSS classes and
custom-bg
; similar shenanigans would be needed for the other configurable values. To supply the customized CSS, you could inline a<style>
element into your HTML using a standard ERB partial or you could serve the CSS through a controller (either through<style src="...">
or@import
). So you'd fake the SASSy goodness with old school multiple CSS classes in your HTML.There's also JavaScript. You'd need some way to identify the elements that need their colors adjusted and then adjust them directly with things like this: