如何在rails中使用google放大器页面的内联样式

时间:2016-11-16 05:27:13

标签: ruby-on-rails erb amp-html

我在rails中使用google amp兼容页面的网站布局有以下rails模板,它正在开发中,但样式表无法在生产中编译

<!doctype html>
<html ⚡>
  <head>
    <title>
      <%= App.title %>
    </title>
    <%= render 'layouts/meta' %>
    <style amp-boilerplate>
      body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}
    </style>
    <style amp-custom>
    <%= Rails.application.assets.find_asset('amp').to_s.gsub('@charset "UTF-8";', '').html_safe %>
    </style>
    <script async src="https://cdn.ampproject.org/v0.js"></script>
  </head>
  <body>
    <%= render 'layouts/header' %>
    <%= yield %>
    <%= render 'layouts/footer' %>
  </body>
</html>

2 个答案:

答案 0 :(得分:3)

看起来并不太难。您可以添加以下帮助程序,我在vyachkonovalov

中找到

将以下内容添加到erb模板中:

<style amp-custom>
  <%= asset_to_string('amp.css').html_safe %>
</style>

ApplicationHelper的助手。它在本地和生产中都能很好地工作。

module ApplicationHelper
  def asset_to_string(name)
    app = Rails.application
    if Rails.configuration.assets.compile
      app.assets.find_asset(name).to_s
    else
      controller.view_context.render(file: File.join('public/assets', app.assets_manifest.assets[name]))
    end
  end

答案 1 :(得分:2)

您可以使用内置的Sass功能来压缩scss文件。

例如,在您的application_helper文件中:

def amp_stylesheet
  amp_css = Rails.application.assets['amp/application'].to_s
  if amp_css.count('\n') > 2
    ::Sass::Engine.new(amp_css, syntax: :scss, style: :compressed).render
  else
    amp_css
  end
end

在你的布局文件中:

<style amp-custom>
  <%= amp_stylesheet.html_safe %>
</style>

此博文可能也很有用:How To Create Custom Stylesheets Dynamically With Rails And Sass