ruby-on-rails – 在Rails中扩展现有布局

我有我的主应用程序布局,但后来我的网站的/ account部分与应用程序布局markupwise具有完全相同的布局,除了/ account页面在布局的内容区域中添加侧边栏.

我不想公然复制应用程序布局并创建几乎冗余的“帐户”布局,而是扩展应用程序布局,在内容区域添加侧边栏.

所以我的应用程序布局中有这样的东西:

<html>
<body>

<div id="content">

<%= yield %>

</div>

</body>
</html>

而且我要

<html>
<body>

<div id="content">

  <div id="sidebar"></div>

  <%= yield %>

</div>

</body>
</html>

有没有办法在不复制代码的情况下实现这一目标?

解决方法

您可以在布局中拥有多个产量,只需为其他产品命名即可:
<html>
<body>
  <div id="content">
    <%= yield :sidebar %>
    <%= yield %>
  </div>
</body>
</html>

您可以使用content_for方法为该产量添加HTML

<% content_for :sidebar do -%>
  <div id="sidebar"></div>
<% end -%>

但是你必须将它添加到你想要有侧边栏的每个视图中.而是创建views / layouts / application_with_sidebar.html.erb

<% content_for :sidebar do -%>
  <div id="sidebar"></div>
<% end -%>

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

Further reading

如果您希望将收益率保持在最小值,则可以嵌套布局.

视图/布局/ application.html.erb

<html>
<body>
  <div id="content">
    <%= yield(:with_sidebar) or yield %>
  </div>
</body>
</html>

视图/布局/ application_with_sidebar.html.erb

<% content_for :with_sidebar do -%>
  <div id="sidebar"></div>
<% end -%>

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

控制器/ accounts_controller.rb

class AccountsController < ApplicationController
  layout 'application_with_sidebar'
  ...
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...