开发者

Rails sublayout

I have a Messages controller, with actions like: Sent messages,Received messages,Send new message. They are displayed to the user in a toolbar form. The thing is, when I render each view, I have to manually render the toolbar as well. So, here's how the code for the views looks like:

sent_messages.html.erb
   <%= render "shared/toolbar" %>
   #  render stuff for sent messages


received_messages.html.erb
   <%= render "shared/toolbar" %>
   # render stuff for received messages


new.html.erb
   <%= render "shared/toolbar" %>
   # render stuff for new message

The views don't look very DRY. Is there a way I could specify that I want the toolbar to render before eve开发者_开发技巧rything else, in the Messages controller?


app/views/layouts/application.html.erb

<html>
<head>
  <title></title>
</head>
<body>
  <div id="content"><%= content_for?(:content) ? yield(:content) : yield %></div>
</body>
</html>

app/views/layouts/messages.html.erb

<% content_for :content do %>
  <%= render "shared/toolbar" %>
  <%= yield %>
<% end %>
<%= render file: "layouts/application" %>


From the documentation:

Suppose you have the following ApplicationController layout:

app/views/layouts/application.html.erb

<html>
<head>
  <title><%= @page_title or "Page Title" %></title>
  <%= stylesheet_link_tag "layout" %>
  <style><%= yield :stylesheets %></style>
</head>
<body>
  <div id="top_menu">Top menu items here</div>
  <div id="menu">Menu items here</div>
  <div id="content"><%= content_for?(:content) ? yield(:content) : yield %></div>
</body>
</html>

On pages generated by NewsController, you want to hide the top menu and add a right menu:

app/views/layouts/news.html.erb

<% content_for :stylesheets do %>
  #top_menu {display: none}
  #right_menu {float: right; background-color: yellow; color: black}
<% end %>
<% content_for :content do %>
  <div id="right_menu">Right menu items here</div>
  <%= content_for?(:news_content) ? yield(:news_content) : yield %>
<% end %>
<%= render template: "layouts/application" %>

That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜