jhlu87
jhlu87

Reputation: 4019

rails content_for not working

I want to have my javascript/coffescript files load only on the pages that use them. So in my application.html.erb file I have the following code in my head

<%= yield :head %>

Then in the specific view that I want to load the javascript I have

<% content_for(:head) do%>
<%= javascript_include_tag 'application' %>
<% end%>

This appears to work initially. When I first go to pages that I do not want javascript in, there are no links to the js files. However, once I've visited the page that has the above code block, the links show up in all subsequent pages I visit (for example the home page). If I then refresh the browser in the home page the links go away again...

This in and of itself isn't really a problem, but I also have this in my application.html.erb head section

<style><%= yield :stylesheets %></style>

and in some layouts, there is css that gets yielded to in there. Here's where it gets really weird. Let's say page A has no js and no additional css, page B has no js but does have additional css, and page C has both js and additional css. Then I do teh following in order:

Visit page A => everything is fine
Visit page B => everything is fine (additional css is loaded)
visit page A again => everything is fine (additional css is not loaded)
visit page C => everything is fine (additional css and js loaded)
visit page A again => NOT GOOD!!! (additional css and js still loaded)

somehow the javascript include tag is also causing my content_for(:stylesheets) stuff to persist even tho i don't want it to. If I do a manual refresh on page A everythign goes back to normal again until I visit page C. I've even tried putting this in my page A view to get rid of the links and still no good

<% content_for(:head) do%>
<% end%>

Any ideas?

Upvotes: 3

Views: 3178

Answers (3)

Waseem Ghafoor
Waseem Ghafoor

Reputation: 1

I used

<% content_for :head do %>
<% end %>

But didn't use <%= content_for :head %> in my relevant layout's head tag which was the problem for me.

More these are equal

<%= content_for :head %>
or
<%= yield :head %>

Upvotes: 0

Andre
Andre

Reputation: 36

Update your config/initializers/assets.rb

Either add your filename.js file or **/*.js inside Rails.application.config.assets.precompile += %w( filename.js)

Run RAILS_ENV=production rake assets:precompile depends on your environment. If you are working locally, skip that command as it will precompile on the fly, as per your config.

Restart your app, should work with turbolinks off and yield from head or body.

Upvotes: 0

Michael Walters
Michael Walters

Reputation: 76

With turbolinks enabled, it won't work. What you need to do is either disable turbolinks or put your javascript and css inside the body of your page.

Upvotes: 4

Related Questions