content_for?Given the following layout and view, what will the final HTML output be?
Layout (application.html.erb):
<html>
<head>
<title>MyApp</title>
<%= yield :head %>
</head>
<body>
<%= yield %>
</body>
</html>View (index.html.erb):
<% content_for :head do %>
<style>body { background: #eee; }</style>
<% end %>
<h1>Welcome</h1>
<p>Hello, world!</p>Remember that content_for stores content for a named block that can be rendered in the layout with yield :name.
The content_for :head block in the view adds the style tag to the :head content. The layout calls yield :head inside the <head> tag, so the style is inserted there. The main yield outputs the rest of the view content inside the <body>.
content_for to add a JavaScript snippet in a Rails layout?You want to add a JavaScript snippet inside the <head> tag of your layout using content_for. Which code in your view will work correctly?
Remember that content_for is a block helper and should be used with <% %> tags, not <%= %>.
Option C correctly uses content_for :head do with ERB tags <% %> to define a block. Option C uses a different name (:javascript) which won't render unless the layout yields :javascript. Option C uses <%= %> which tries to output the return value, causing an error. Option C is missing the do keyword, so it's invalid syntax.
content_for?(:sidebar) after rendering this view?Given this layout and view, what will content_for?(:sidebar) return in the layout?
Layout snippet:
<body>
<%= yield %>
<% if content_for?(:sidebar) %>
<aside><%= yield :sidebar %></aside>
<% end %>
</body>View snippet:
<h1>Page Title</h1> <%# No content_for :sidebar block here %>
If no content was stored for a named block, content_for? returns false.
Since the view does not define any content_for :sidebar block, content_for?(:sidebar) returns false. This prevents rendering the sidebar section in the layout.
content_for block not appear in the layout?Consider this layout and view. The style block inside content_for :head does not appear in the final HTML. Why?
Layout (application.html.erb):
<html>
<head>
<title>Site</title>
</head>
<body>
<%= yield %>
</body>
</html>View (show.html.erb):
<% content_for :head do %>
<style>body { color: red; }</style>
<% end %>
<h1>Hello</h1>Check if the layout includes yield :head where the content is expected.
The content_for block stores content for a named block, but the layout must explicitly call yield :head to render it. Since the layout lacks yield :head in the <head>, the style is never output.
content_for calls with the same name in a single view?In a Rails view, if you call content_for :scripts multiple times with different blocks, what will yield :scripts output in the layout?
Think about how Rails accumulates content for named blocks.
Rails appends content from multiple content_for calls with the same name. When yield :scripts is called, it outputs all concatenated content in the order they were defined.