如何在视图中多次渲染多个部分?

时间:2012-07-22 04:54:28

标签: ruby-on-rails haml

我有一个包含许多模块的页面,这些模块具有可变部分,例如标题,子标题,页脚,正文和id。我首先创建了一个布局,并使用局部变量和主块来渲染布局以填充模板。

布局:

.container{:id => local_assigns[:id].present? ? id : nil}
    .header
        = title
        = subtitle
    .body
        = yield
    .footer
        = footer

查看:

= render :layout => "shared/example", :locals => {:title => 'Heading', :subtitle => 'Sub heading', :footer => 'closing part'} do
    body of the template

这很好用,但是现在我想传递块的字幕和页脚,记住页面中会有多个这种布局的实例。到目前为止,我能够解决这个问题的唯一方法是使用capture_haml helper

使用Haml作为局部变量进行查看:

- exampleSubtitle = capture_haml do
    %h3 subtitle
    %button action
= render :layout => "shared/example", :locals => {:title => 'Heading', :subtitle => exampleSubtitle, :footer => 'closing part'} do
        body of the template

这个例子有点过时,以澄清问题。在实践中,我担心:locals哈希增长到“丑陋的哈姆”大小,并希望尽可能防止这种情况。

有没有办法定义上下文内容块以保持清洁?

一厢情愿的观点:

= render :layout => "shared/example", :locals => {:title => 'Heading'} do
    - content_for :subtitle do
        %h3 subtitle
        %button action
    - content_for :footer do
        %a{href => "#top"} top
    body of the template
好心的布局:

.container{:id => local_assigns[:id].present? ? id : nil}
    .header
        = title
        - if content_for?(:subtitle)
            = yield :subtitle
    .body
        = yield
    - if content_for?(:footer)
    .footer
        = yield :footer

0 个答案:

没有答案