Posted By

sgtrock on 12/27/09


css javascript html rails unobtrusive stylesheet unobtrusivejavascript

Versions (?)

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

 / Published in: Rails

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.

  1. [application_helper.rb]
  2. module ApplicationHelper
  3. def requires_javascript(path)
  4. content_for :page_dependencies do
  5. javascript_include_tag path
  6. end
  7. end
  9. def requires_stylesheet(path)
  10. content_for :page_dependencies do
  11. stylesheet_link_tag path
  12. end
  13. end
  14. end
  16. [my_layout.html.erb]
  17. <html>
  18. <head>
  19. <%= yield :page_dependencies %>
  20. ...
  21. </head>
  22. ...
  23. </html>
  25. [my_view.html.erb]
  26. <% requires_javascript "my-view-specific-javascript" %>
  27. <% requires_stylesheet "my-view-specific-stylesheet" %>

Report this snippet  


RSS Icon Subscribe to comments
Posted By: sgtrock on December 27, 2009

I also use this technique to implement Google Maps in the view using the YM4R plugin. Much more declarative than forcing a way to inject the GMap header stuff into the HEAD in a jumble with everything else.

In application_helper.rb:

def requiresgooglemaps contentfor :pagedependencies do concat GMap.header end end

Posted By: sgtrock on December 27, 2009

Trying the code again with markdown...

def requires_google_maps
  content_for :page_dependencies do
    concat GMap.header


You need to login to post a comment.