Rails 4 Page-specific JavaScript and CSS

Ever needed to customize a page with JavaScript or CSS that will never be used elsewhere? Here’s a method I found to work especially well and keeps the code with the template so it’s easily accessible.

Create assets initializer: config/initializers/assets.rb

Rails.application.config.assets.version = '1.0'

Rails.application.config.assets.paths += ["#{Rails.root}/app/views/"]
Rails.application.config.assets.precompile += Dir.glob("#{Rails.root}/app/views/**/*.scss").map { |fn| fn.gsub("#{Rails.root}/app/views/","") }
Rails.application.config.assets.precompile += Dir.glob("#{Rails.root}/app/views/**/*.js.erb").map { |fn| fn.gsub("#{Rails.root}/app/views/","") }


Page-specific Javascript at app/views/home/foo.js.erb

// Your JavaScript


Page-specific CSS at app/views/home/foo.css.scss

/* Your page-specific styles */


View template at app/views/home/foo.html.erb

<%= stylesheet_link_tag "home/foo" %>
<%= javascript_include_tag "home/foo" %>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s