【问题标题】:Rails3.1 - How do I include css files in some views but not others?Rails3.1 - 如何在某些视图中包含 css 文件而不在其他视图中包含 css 文件?
【发布时间】:2014-05-31 03:34:13
【问题描述】:

似乎在 rails 3.1 中,所有的 css.scss 文件都被合并到一个文件中。如果我希望一个 css 文件只包含在某些视图中,我该怎么办?就像我希望 admin.css.scss 包含在管理页面中,而 main.css.scss 包含在主页/关于/联系页面中。

【问题讨论】:

    标签: ruby-on-rails-3 compass-sass


    【解决方案1】:

    在 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'
    

    【讨论】:

    • %head 和 yield :head 位有什么作用?
    • 在 Haml 中: %head = yield :head 将在 HTML 中生成 标记,并通过 yield 从另一个页面插入代码
    【解决方案2】:

    让我添加一个对我有用的解决方案。

    如上一个答案中所述,您可能希望删除

     *= require_tree . 
    

    来自 application.css 文件的语句。

    我保留了

     *= require_self
    

    跨应用程序共享样式的声明。

    然后在我的 application.html 文件中,我使用以下语句仅包含 application.csscontroller.controller_name.css视图中的样式表。

    = stylesheet_link_tag "application", controller.controller_name
    = javascript_include_tag "application", controller.controller_name
    

    正如你所看到的,JavaScript 文件也是如此。

    【讨论】:

      【解决方案3】:

      另请参阅:
      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 文件!

      【讨论】:

      • +1 用于实际指定要查看的部分,而不是转储相同的旧链接。
      • 谢谢。是的,这是一个冗长的页面,他们更改了部分编号
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 2010-12-05
      • 2019-07-30
      • 2019-09-10
      • 1970-01-01
      • 2021-11-09
      相关资源
      最近更新 更多