【发布时间】:2014-05-31 03:34:13
【问题描述】:
似乎在 rails 3.1 中,所有的 css.scss 文件都被合并到一个文件中。如果我希望一个 css 文件只包含在某些视图中,我该怎么办?就像我希望 admin.css.scss 包含在管理页面中,而 main.css.scss 包含在主页/关于/联系页面中。
【问题讨论】:
标签: ruby-on-rails-3 compass-sass
似乎在 rails 3.1 中,所有的 css.scss 文件都被合并到一个文件中。如果我希望一个 css 文件只包含在某些视图中,我该怎么办?就像我希望 admin.css.scss 包含在管理页面中,而 main.css.scss 包含在主页/关于/联系页面中。
【问题讨论】:
标签: ruby-on-rails-3 compass-sass
在 Rails 3.1 中,如果您的 application.css 如下所示,您的所有样式表都将合并到 application.css 中:
/*
* This is a manifest file that'll automatically include all the stylesheets available in this directory
* and any sub-directories. You're free to add application-wide styles to this file and they'll appear at
* the top of the compiled file, but it's generally better to create a new file per style scope.
*= require_self
*= require_tree .
*/
这是由于 *=require_tree 。
您可以要求一个特定的样式表:
*= require main
否则,在你的布局中,你写:
%head
= yield :head
在您的页面中:
= content_for :head do
= stylesheet_link_tag 'stylesheet'
【讨论】:
让我添加一个对我有用的解决方案。
如上一个答案中所述,您可能希望删除
*= require_tree .
来自 application.css 文件的语句。
我保留了
*= require_self
跨应用程序共享样式的声明。
然后在我的 application.html 文件中,我使用以下语句仅包含 application.css 和 controller.controller_name.css视图中的样式表。
= stylesheet_link_tag "application", controller.controller_name
= javascript_include_tag "application", controller.controller_name
正如你所看到的,JavaScript 文件也是如此。
【讨论】:
另请参阅:
http://guides.rubyonrails.org/layouts_and_rendering.html
(参见第 2.2.14 节“查找布局”)
您可以为不同的控制器设置不同的布局!
例如在 app/views/layouts 你可以有 application.haml 和 admin.haml 在 app/controllers 下你会有一个 admin_controller.rb
Rails 会尝试查找与控制器同名的布局。
您还可以覆盖此行为并指定要使用的布局,例如:
class ItemsController < ApplicationController
layout "admin"
#...
end
然后,您将在 app/stylesheets 下为这个新布局创建一个 admin.scss 文件!
【讨论】: