Rails子布局

时间:2011-04-16 14:49:38

标签: ruby-on-rails views

我有一个消息控制器,其操作类似于:Sent messagesReceived messagesSend new message。它们以工具栏形式显示给用户。问题是,当我渲染每个视图时,我也必须手动渲染工具栏。所以,这里的视图代码如下:

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

视图看起来不太干净。有没有一种方法可以在Messages控制器中指定我希望toolbar在其他所有内容之前呈现?

2 个答案:

答案 0 :(得分:0)

来自documentation

假设您有以下ApplicationController布局:

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>

在NewsController生成的页面上,您想隐藏顶层菜单并添加右侧菜单:

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" %>

就是这样。新闻视图将使用新布局,隐藏顶部菜单并在“内容”div中添加新的右侧菜单。

答案 1 :(得分:0)

应用/视图/布局/ application.html.erb

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

应用/视图/布局/ messages.html.erb

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