content_for are not rendering in partial views

1.5k views Asked by At

I have a rails app which uses a layout

The simplified version looks like this:

<html>
  <head>
    <%= render 'layouts/head' # renders the "layouts/_head.html.erb" partial correctly  
                              # the most head (css/js) content gets implemented here %>
  </head>
  <body>

    <%= yield # renders the current action %>

    <!-- implement alls scripts which should be exectued on the bottom of the page -->
    <%= content_for :scripts_bottom %>
  </body>
</html>

in my `layouts/_head.html.erb' I use

 <%= content_for :scripts_head %>
 <!-- it seems `content_for` instead of `yield` appends content -->

In my partials I place the following snippets to append them :scripts_head. (some of my partials should put javaScripts

<% content_for :scripts_head do %>
    <%= javascript_include_tag 'some_script' %>
<% end %>

The content_for in the `layouts/head' renders nothing

How can I resolve that?

It looks like that partials are not able to append their content_for content when the content_for :blah do is placed BEHIND the echoing content_for / yield tag.

If I try try content_for :scripts_bottom it will get rendered at the bottom of the page.

Thanks in advance

Rails 3.2.14 ruby 2.0.0p247

3

There are 3 answers

1
Dudo On

instead of provide, try <%= content_for :scripts_head %>

1
AntelopeSalad On

If you want to use content_for then you need to yield it in your head instead of render.

So your header would look like:

<%= yield :scripts_head %>

Alternatively you can remove the content_for in your partial and just have the JS by itself like this:

<%= javascript_include_tag 'some_script' %>

Then you wouldn't have to change your layout file.

0
DGM On

In your layouts/head partial, use yield :scripts_head not content_for