Search code examples
ruby-on-railserbamp-html

How to use inline styles for google amp pages in rails


I have the following rails template for our site layout for google amp compatible pages in rails, it is working in development however the stylesheet does not compile in production

<!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>

Solution

  • Looks like it is not too difficult. You can add the following helper, I found from vyachkonovalov

    Add the following to the erb template:

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

    And the helper to ApplicationHelper. It works perfectly locally and in production.

    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