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


/ Published in: Rails
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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
  8.  
  9. def requires_stylesheet(path)
  10. content_for :page_dependencies do
  11. stylesheet_link_tag path
  12. end
  13. end
  14. end
  15.  
  16. [my_layout.html.erb]
  17. <html>
  18. <head>
  19. <%= yield :page_dependencies %>
  20. ...
  21. </head>
  22. ...
  23. </html>
  24.  
  25. [my_view.html.erb]
  26. <% requires_javascript "my-view-specific-javascript" %>
  27. <% requires_stylesheet "my-view-specific-stylesheet" %>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.