Charlie
Charlie

Reputation: 10307

Nested layouts in ruby on rails

I'm new to rails and am trying to work out how to get nested layouts working; I'm assuming they're a bit like .net master pages?

I've followed this guide and I've created an application.erb.html in my layout directory which contains this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title><%= @page_title or 'Page Title' %></title>
  <%= stylesheet_link_tag 'layout' %>
  <style type="text/css"><%= yield :stylesheets %></style>
</head>
<body>

<%= yield(:content) or yield %>

</body>
</html>

and have modified one of my existing layouts to this:

<% content_for :stylesheets do %>

<% end -%>

<% content_for :content do %>
  <p style="color: green"><%= flash[:notice] %></p>
  <%= yield %>
<% end -%>

<% render :file => 'layouts/application' %>

When I go to one of my views in the browser, absolutely nothing is rendered; when I view source there is no html.

I'm sure there's something elementary I've missed out, can anyone point it out please?!

Upvotes: 12

Views: 6739

Answers (3)

kbjerring
kbjerring

Reputation: 623

Here is a different approach to nested layouts that may come out handy.

Upvotes: 0

insane.dreamer
insane.dreamer

Reputation: 2072

The original article had an error, and your solution is correct. Here's the reason:

The output of ruby code in an ERB (view) that is encased in <%= %> gets added to the HTML that's generated and sent to the browser. The output of ruby code that is encase in <% %> does not get added to the HTML. So calling <% render :partial ... %> has no effect since the result of that ruby code (fetching the partial) isn't added to the generated HTML file.

<% %> is generally reserved for conditionals and loops, as you have in the example above.

Upvotes: 4

Charlie
Charlie

Reputation: 10307

I've worked out the solution, although it's not what's given in this article

I've replaced this line

<% render :file => 'layouts/application' %>

with

<%= render :file => 'layouts/application' %>

I'm not sure if the article is wrong, or I've found the wrong way to fix it! Please let me know!

Cheers

Upvotes: 29

Related Questions