Haml在布局中渲染多个部分

时间:2010-09-24 21:13:21

标签: html ruby-on-rails-3 haml partial partials

如何正确缩进代码?

应用程序/视图/布局/ shared.html.haml:

= render :partial => "shared/head"
= yield
= render :partial => "shared/footer"

应用程序/视图/共享/ _head.html.haml:

!!!XML
!!!1.1
%html{"xml:lang" => "pl", :xmlns => "http://www.w3.org/1999/xhtml"}
  %head
    %title
      some title
  %body
    .container

应用程序/视图/共享/ index.html.haml:

%p
  Hello World!

应用程序/视图/共享/ _footer.html.haml:

.footer
  Some copyright text

呈现HTML输出:

<!DOCTYPE html> 
<html xml:lang='pl' xmlns='http://www.w3.org/1999/xhtml'> 
  <head> 
    <title> 
      some title
    </title> 
  </head> 
  <body> 
    <div class='container'></div> 
  </body> 
</html> 
<p> 
  Hello World!
</p> 
<div id='footer'> 
 Some copyright text
</div> 

2 个答案:

答案 0 :(得分:5)

您应该使用app/views/layoutyield实际内容:

Example

更新

app/views/layout/shared.html.haml

!!! 1.1
%html
  = render "shared/head"
  %body
    .container
      = yield
  = render "shared/foot"

答案 1 :(得分:1)

看起来我在这里聚会很晚,但也许其他人会遇到这个并需要处理同样的问题(就像我今晚做的那样)。

在我的情况下,我有一个更复杂的开放HTML标签设置,以及几个不同的布局,所以我不想要所有的重复。我的开放HTML标记具有不同IE版本的条件,最初看起来像这样:

- # /app/views/layouts/shared/_head.html.haml

!!! 5
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie ie6"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="no-js ie ie7"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="no-js ie ie8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="no-js ie ie9"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
%html{ 'xml:lang' => 'en', lang: 'en', class: 'no-js'}
  <!--<![endif]-->
  %head
  - # and so on...

我遇到同样的问题</html>过早终止,所以我从_head部分中删除了HTML标记(留下头标记)并创建了以下帮助来处理问题:

# /app/helpers/application_helper.rb

module ApplicationHelper
  def render_html_tag(&block)
    markup = capture_haml &block
    haml = Haml::Engine.new <<-HAML
!!! 5
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie ie6"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="no-js ie ie7"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="no-js ie ie8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="no-js ie ie9"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
%html{ 'xml:lang' => 'en', lang: 'en', class: 'no-js'}
  <!--<![endif]-->
  = markup
HAML

    obj = Object.new
    haml.def_method(obj, :render, :markup)
    obj.render(markup: markup)
  end
end

它有点乱,也许它可以清理一下,但主要的想法是利用haml engine's #def_method,它允许布局看起来像这样:

- # /app/views/layout/application.html.haml

= render_html_tag do
  = render 'layouts/shared/head'
  %body
    = yield
  = render 'layouts/shared/footer'