1

I'm starting with Rails 4 and I have a couple of questions about assets. How can I specify that a CSS just must be included in some view? I have the same question about a JS file. I have added a JS file to app/assets/javascripts/viewname.js however it is included in every page. I would like it to be seen just in viewname view.

Help me please! Thanks

1 Answers1

2

Save the file as /vendor/assets/javascripts/viewname.js and include it in your view with:

<%= javascript_include_tag 'viewname' %>

To include the JS file in the HTML header

Use content_for in a view file to collect content that will be rendered later.

<% content_for :head %>
  <%= javascript_include_tag 'viewname' %>
<% end %>

Call yield in the layout template to render the collected content:

<head>
  ...
  <%= yield :head %>
</head>

To automatically include a javascript file named after the current controller, you could also put this in your layout template file:

<head>
  ...
  <%= javascript_include_tag params[:controller] %>
  <%= javascript_include_tag "#{params[:controller]}_#{params[:action]}" # variant with action name %>
</head>

But that will give 404 errors for a controllers/actions without a javascript file.

zwippie
  • 15,050
  • 3
  • 39
  • 54
  • this solution involves that the – user2850645 Oct 19 '13 at 15:12
  • 1
    Updated answer with part about including in ``. – zwippie Oct 19 '13 at 19:10
  • 1
    it should be <% content_for : head do %> – dc10 Oct 27 '14 at 21:33