Ruby布局继承

时间:2013-08-13 15:33:12

标签: ruby-on-rails rubygems

我想知道ruby中是否有任何布局继承实现。 在symfony中,您可以这样做:

layoutmain.html
Give <head> and all that here
<body>
<h3>{{title}}</h3>

{{block view}}
<div class="row">
<div class="span3">
{{content}}
</div>
</div>

{{end block}}


</body>


layout2.html
{{inherits layoutman}}
{{block view}}
 <div class="container">
Structure it differently
 </div>
{{end block}}

可以这么说,它让你继承整个模板并覆盖不同布局的部分。因此脚本等保留在主模板中,但您可以更改视图结构。因此,您可以在第一个布局中重复使用一些代码

我在github上找到了一些液体继承项目,但看起来过时了

2 个答案:

答案 0 :(得分:3)

我使用以下方法来实现布局的“嵌套”,这是我发现最有用的布局继承形式。

在主应用程序助手模块app/helpers/application_helper.rb中,我定义了辅助方法parent_layout

module ApplicationHelper
  def parent_layout(layout)
    @view_flow.set(:layout, self.output_buffer)
    self.output_buffer = render(:file => layout)
  end
end

此帮助程序负责捕获当前布局的输出,然后在父yield s时插入子布局来呈现指定的父布局。

然后在我的视图中,我可以按如下方式设置布局继承。我从我的主应用程序布局app/views/layouts/application.html.erb开始,这是此配置中的布局:

<div class="content">
  <h1><%= content_for?(:title) ? yield(:title) : 'Untitled' %></h1>
  <div class="inner">
    <%= yield %>
  </div>
</div>
<%= parent_layout 'layouts/container' %>

对辅助方法parent_layout的调用指定application.html.erbcontainer.html.erb的子布局。然后我按如下方式定义布局app/views/layouts/container.html.erb

<!DOCTYPE html>
<html>
<head>
  <title>Sample</title>
</head>
<body>
  <%= yield %>
</body>
</html>

yield中的container.html.erb产生“派生”(或子)布局application.html.erb,即它将渲染application.html.erb的输出插入<body> } container.html.erb。请注意,parent_layout调用需要在模板的末尾 ,因为它会捕获布局的输出,直到它被调用为止。

这是基于this文章,但已更新为在Rails 3.2中工作(希望稍后)。我没有在Rails 4中尝试过,但你可以得到类似的工作。

答案 1 :(得分:0)

Ruby on Rails视图有一个名为“partials”的功能。我局部是一个生成一些html的视图,可以包含在其他视图中。 partials还可以接受自定义其行为的参数(局部变量)。部分可以包括其他部分。

这可能是开始了解这一点的好地方:http://guides.rubyonrails.org/layouts_and_rendering.html

我从来没有像你所描述的那样做某种布局继承的事情,但是我可以想象用partials很容易做到这一点并传递ruby变量,说明在哪种情况下使用哪个部分。