Return to Snippet

Revision: 21967
at December 27, 2009 00:35 by sgtrock


Initial Code
[application_helper.rb]
module ApplicationHelper
  def requires_javascript(path)
    content_for :page_dependencies do
      javascript_include_tag path
    end
  end
  
  def requires_stylesheet(path)
    content_for :page_dependencies do
      stylesheet_link_tag path
    end
  end
end

[my_layout.html.erb]
<html>
  <head>
    <%= yield :page_dependencies %>
    ...
  </head>
  ...
</html>

[my_view.html.erb]
<% requires_javascript "my-view-specific-javascript" %>
<% requires_stylesheet "my-view-specific-stylesheet" %>

Initial URL


Initial Description
I used to directly inject javascript and CSS into my HEAD elements just like you see in all of the tutorials online and in books. Recently I decided to try a different approach, and I feel this is more in keeping with the ruby and rails "declaration" syntax. It has the added benefit of promoting unobtrusive javascript coding and factoring out page-specific CSS into its own file.

Initial Title
Requiring javascript and CSS in Rails without directly injecting code into the HEAD element

Initial Tags
css, javascript, html, rails

Initial Language
Rails