根据rails 4中的页面显示不同的样式表

时间:2014-10-25 18:08:17

标签: html ruby-on-rails ruby ruby-on-rails-4

我正在尝试根据页面呈现不同的CSS。我做了一些研究 How does one load a CSS framework in Rails 3.1? https://github.com/rails/rails/issues/1981 当然还有资产管道上的导轨。 我想要的是索引(主页)呈现一个css文件(welcome.css.scss),其他人呈现users.css.scss。

现在,当您导航到页面时,它会呈现welcome.css.scss,然后当我点击登录时,它仍然呈现welcome.css.scss。但刷新页面后,它将呈现user.css.scss

我更新了我的assets.rb文件:

Rails.application.config.assets.precompile += %w( welcome.css )
Rails.application.config.assets.precompile += %w( users.css )

然后我创建了welcome.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>Blocmarks</title>
    <%= stylesheet_link_tag    "welcome" %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>
  </head>
  <body>  
    <%= yield %>
  </body>
</html>

和users.html.erb文件

<!DOCTYPE html>
<html>
  <head>
    <title>Blocmarks</title>
    <%= stylesheet_link_tag    'users' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

我从application.css.scss中删除了require。目前文件中唯一的东西是@import&#39; bootstrap&#39 ;; 当然,我有一个欢迎和user.css.scss。

控制台的结果: - 导航到主页

Started GET "/" for 127.0.0.1 at 2014-10-25 13:04:11 -0500
  ActiveRecord::SchemaMigration Load (0.3ms)  SELECT "schema_migrations".* FROM "schema_migrations"
Processing by WelcomeController#index as HTML
  Rendered welcome/index.html.erb within layouts/welcome (13.0ms)
Completed 200 OK in 471ms (Views: 446.7ms | ActiveRecord: 0.0ms)

导航至用户/登录

Started GET "/users/sign_up" for 127.0.0.1 at 2014-10-25 13:04:57 -0500
Processing by Devise::RegistrationsController#new as HTML
  Rendered devise/shared/_links.erb (2.7ms)
  Rendered devise/registrations/new.html.erb within layouts/devise (615.4ms)
Completed 200 OK in 896ms (Views: 890.9ms | ActiveRecord: 0.9ms)

刷新用户/签名页:

Started GET "/users/sign_up" for 127.0.0.1 at 2014-10-25 13:06:02 -0500
Processing by Devise::RegistrationsController#new as HTML
  Rendered devise/shared/_links.erb (0.8ms)
  Rendered devise/registrations/new.html.erb within layouts/devise (7.4ms)
Completed 200 OK in 308ms (Views: 306.3ms | ActiveRecord: 0.0ms)

我还创建了一个带有完整控制台结果的要点,以显示它首先是GETting: https://gist.github.com/tjperry07/b3093c0b7f16b5e000b0

1 个答案:

答案 0 :(得分:6)

这是因为rails turbolinks而发生的。 它可以更快地在您的Web应用程序中生成以下链接。它不是让浏览器在每个页面更改之间重新编译JavaScript和CSS,而是使当前页面实例保持活动状态,并仅替换正文中的正文和标题。

如果您查看guidesturbolinks docs。它清楚地表明了

  

如果使用turbolinks gem(默认情况下包含在Rails 4中),则包含'data-turbolinks-track'选项,该选项会导致turbolinks检查资产是否已更新,如果是,则将其加载到页面中

<强> FIX:

将样式表标签替换为:

<%= stylesheet_link_tag "welcome", media: "all", "data-turbolinks-track" => true %>
<%= stylesheet_link_tag "users", media: "all", "data-turbolinks-track" => true %>